import json
import pymysql.cursors


def get_query_result(sql, data=None):
    with pymysql.connect(host='localhost', user='root', password='test', database='db') as conn:
        with conn.cursor() as cursor:
            cursor.execute(sql, data)
            return cursor.fetchall()


def execute_query(sql, data=None):
    with pymysql.connect(host='localhost', user='root', password='test', database='db') as conn:
        with conn.cursor() as cursor:
            cursor.execute(sql, data)
            conn.commit()


def get_questions(path):
    with open(path, 'r') as f:
        questions_json = json.load(f)
        questions = questions_json['questions']

    return questions


def create_tables():
    with open('../sql/ddl.sql', 'r') as f:
        sql = f.read()
        for stmt in sql.split(';'):
            if stmt.strip():
                execute_query(stmt)


def insert_question_answer_data(questions):
    inserted_answers = set()
    inserted_symptoms = set()
    for question in questions:
        sql = "INSERT IGNORE INTO `Question` (`question_id`, `question_text`) VALUES (%s, %s)"
        execute_query(sql, (question['id'], question['text']))

        symptom = question['symptom']
        if question['symptom'] not in inserted_symptoms:
            inserted_symptoms.add(symptom)
            sql = "INSERT IGNORE INTO `Symptom` (`symptom`) VALUES (%s)"
            execute_query(sql, (symptom,))

        for answer in question['answers']:
            if answer not in inserted_answers:
                inserted_answers.add(answer)
                sql = "INSERT IGNORE INTO `Answer` (`answer_text`) VALUES (%s)"
                execute_query(sql, (answer,))

            answer_id = get_query_result(f"SELECT * FROM Answer WHERE answer_text = '{answer}'")[0][0]
            sql = "INSERT IGNORE INTO `Question_Answer` (`question_id`, `answer_id`) VALUES (%s, %s)"
            execute_query(sql, (question['id'], answer_id))

        if symptom:
            symptom_id = get_query_result(f"SELECT * FROM Symptom WHERE symptom = '{symptom}'")[0][0]
            sql = "INSERT IGNORE INTO `Symptom_Question` (`symptom_id`, `question_id`) VALUES (%s, %s)"
            execute_query(sql, (symptom_id, question['id']))


def get_questionnaire_responses():
    responses = []

    with open('../json/response_1.json', 'r') as f:
        responses.append(json.load(f))

    with open('../json/response_2.json', 'r') as f:
        responses.append(json.load(f))

    return responses


def insert_patient_data(questionnaire_responses):
    for response in questionnaire_responses:
        questionnaire_id = None
        if response['identifier']['type']['text'] == 'Questionnaire Id':
            questionnaire_id = response['identifier']['value']

        for patient in response.get('contained', []):
            patient_id = None
            for identifier in patient['identifier']:
                if identifier['type']['text'] == 'Patient Number':
                    patient_id = identifier['value']

            sql = "INSERT IGNORE INTO `Patient` (`patient_id`, `first_name`, `last_name`, `address`, `gender`, `birth_date`) VALUES (%s, %s, %s, %s, %s, %s)"
            execute_query(sql, (patient_id, patient['name'][0]['given'], patient['name'][0]['family'],
                                patient['address'][0]['text'], patient['gender'], patient['birthDate']))

            sql = "INSERT IGNORE INTO `Questionnaire` (`questionnaire_id`, `patient_id`) VALUES (%s, %s)"
            execute_query(sql, (questionnaire_id, patient_id))

        for item in response.get('item', []):
            question_text = item['text']
            question_id = get_query_result(f"SELECT * FROM Question WHERE question_text = '{question_text}'")[0][0]

            for answer in item['answer']:
                answer_text = answer['valueString']
                answer_id = get_query_result(f"SELECT * FROM Answer WHERE answer_text = '{answer_text}'")[0][0]
                sql = "INSERT IGNORE INTO `Questionnaire_Response` (`questionnaire_id`, `question_id`, `answer_id`) VALUES  (%s, %s, %s)"
                execute_query(sql, (questionnaire_id, question_id, answer_id))


def main():
    create_tables()
    questions = get_questions('../json/questions.json')
    insert_question_answer_data(questions)

    questionnaire_responses = get_questionnaire_responses()
    insert_patient_data(questionnaire_responses)


if __name__ == '__main__':
    main()
