if __name__ == "__main__":
    import os
    import sys

    sys.path.append(os.getcwd())

import json
from sqlalchemy import text

from app import *
import Models


def update_all():
    update_interest_options()
    update_project_type_options()
    update_info_nuggets()
    update_questions()


def update_interest_options():
    with open("StaticData/interest_options.json", 'r') as f:
        interest_options = json.loads(f.read())
    for i in interest_options:
        if Models.InterestModel.query.get(i['id']):
            db.engine.execute(text(f"UPDATE interest SET de='{i['de']}', en='{i['en']}' WHERE id='{i['id']}'"))
        else:
            db.engine.execute(text(
                f"INSERT INTO interest (de, en, id) VALUES ('{i['de']}', '{i['en']}', '{i['id']}')"))


def update_project_type_options():
    with open("StaticData/project_type_options.json", 'r') as f:
        project_type_options = json.loads(f.read())
    for i in project_type_options:
        if Models.ProjectTypeModel.query.get(i['id']):
            db.engine.execute(text(f"UPDATE project_types SET de='{i['de']}', en='{i['en']}' WHERE id='{i['id']}'"))
        else:
            db.engine.execute(text(
                f"INSERT INTO project_types (de, en, id) VALUES ('{i['de']}', '{i['en']}', '{i['id']}')"))


def update_info_nuggets():
    with open("StaticData/info_nuggets.json", 'r') as f:
        info_nuggets = json.loads(f.read())
    for i in info_nuggets:
        if Models.InfoNuggetModel.query.get(i['id']):
            db.engine.execute(text(
                f"UPDATE info_nuggets SET name='{i['name']}', answers_en= ARRAY {_to_str(i['answers_en'])}, answers_de= ARRAY {_to_str(i['answers_de'])} WHERE id='{i['id']}'"))
        else:
            db.engine.execute(text(
                f"INSERT INTO info_nuggets (id, name, answers_en, answers_de) VALUES ('{i['id']}', '{i['name']}', ARRAY {_to_str(i['answers_en'])}, ARRAY {_to_str(i['answers_de'])})"))


def update_questions():
    with open("StaticData/questions.json", 'r') as f:
        questions = json.loads(f.read())
    for i in questions:
        if Models.QuestionsModel.query.get(i['id']):
            db.engine.execute(text(
                f"UPDATE questions SET official='{i['official']}', question_en='{i['question_en']}', question_de='{i['question_de']}', placeholder_en='{i['placeholder_en']}', placeholder_de='{i['placeholder_de']}' WHERE id='{i['id']}'"
            ))
        else:
            db.engine.execute(text(
                f"INSERT INTO questions (id, official, question_en, question_de, placeholder_en, placeholder_de) VALUES ('{i['id']}', '{i['official']}', '{i['question_en']}', '{i['question_de']}', '{i['placeholder_en']}', '{i['placeholder_de']}')"
            ))


def _to_str(str_list):
    return "['" + "', '".join(str_list) + "']"


if __name__ == "__main__":
    update_all()
