import functools
from flask import (Blueprint, flash, g, redirect, render_template, request, session, url_for)
from Icd10ConditionsMatching.db_interface import (
    get_db,select_remaing_trials_to_analyze, 
    select_analyzed_trials,
    select_unmatched_trials,
    get_trial_conditions_and_proposed_matches,
    store_validation,
    get_trial_summary,
    get_list_icd10_codes,
    record_suggested_matches,
    )
from datetime import datetime

#### First Blueprint: Checking Data
bp = Blueprint("validation", __name__, url_prefix="/validation")



@bp.route("/",methods=["GET"])
def remaining():
    db_conn = get_db()


    to_validate = select_remaing_trials_to_analyze(db_conn)
    validated = select_analyzed_trials(db_conn)
    unmatched_list = select_unmatched_trials(db_conn)
 
    
    return render_template(
        "validation_index.html", 
        list_to_validate=to_validate,
        validated_list = validated,
        unmatched_list = unmatched_list
        )


@bp.route("/<nct_id>", methods=["GET","POST"])
def validate_trial(nct_id):
        
    if request.method == "GET":
        db_conn = get_db()

        condition_list =  get_trial_conditions_and_proposed_matches(db_conn, nct_id)
        summary_dats = get_trial_summary(db_conn, nct_id)

        return render_template(
            "validation_of_trial.html", 
            nct_id=nct_id,
            condition_list=condition_list,
            summary_dats=summary_dats,
            )
    elif request.method == "POST":
        db_conn = get_db()

        list_of_insert_data = []
        
        db_conn = get_db()

        condition_list =  get_trial_conditions_and_proposed_matches(db_conn, nct_id)

        print(request.form)

        if "submission" in request.form:
            #if it is a submission: 
                #grab all match ids from db
                #if match id in submitted form, mark as approved, otherwise mark as rejected
            for condition in condition_list:
                id = condition[0]
                list_of_insert_data.append((request.form.get(str(id),"rejected"), datetime.now(),id))
               
            store_validation(db_conn, list_of_insert_data)
            return redirect(url_for("validation.remaining"))
        elif "marked_unmatched" in request.form:
            #if this was marked as "unmatched", store that for each entry.
            for condition in condition_list:
                id = condition[0]
                list_of_insert_data.append(( "unmatched", datetime.now(), id))

            store_validation(db_conn, list_of_insert_data)
            return redirect(url_for("validation.remaining"))
        elif "alternate_submission" in request.form:
            code = request.form["alt_sub"]
            code = code.strip().replace(".",'').ljust(7,"-")

            condition = request.form["condition"].strip()

            codelist = get_list_icd10_codes(db_conn)
            if code in codelist:
                record_suggested_matches(db_conn, nct_id, condition, code)
                return redirect(request.path)
            else:
                record_suggested_matches(db_conn, nct_id, condition + "| Code not in GBD list", code)
                return """
                Entered `{}`, which is not in the list of available ICD-10 codes. <a href={}>Return to trial summary</a>
                """.format(code.strip("-"),request.path), 422
        

