from flask import Blueprint, request, session, jsonify

from helix.calculators.calculator import Calculator
from helix.presenters.panel_presenter import ProjectPresenter
from helix.session_manager import SessionManager
from helix.constants import redis_constant, sql_constant
from helix.seismic_validator_user_values import SeismicValidatorUserValues
from helix.validators.seismic_anchor_validator import SeismicAnchorValidator

api = Blueprint('api', __name__, template_folder='templates')


@api.route("/panel_data")
def panel_data():
    db_session = sql_constant.sql_session_maker()
    session_manager = SessionManager(session, redis_constant.redis_store, db_session)
    user_values = session_manager.user_values()
    calculator = Calculator(user_values)
    system_type = user_values.system_type()
    module_type = user_values.module_type()
    data = ProjectPresenter(system_type, module_type).get_panel_data(calculator.get_computed_csv_columns(), calculator.subarrays)
    db_session.close()
    return jsonify({'panel_data': data})


@api.route("/update_panel_data", methods=['POST'])
def update_panel_data():
    db_session = sql_constant.sql_session_maker()
    session_manager = SessionManager(session, redis_constant.redis_store, db_session)
    user_seismic_data = request.get_json()
    user_values = SeismicValidatorUserValues(session_manager.user_values(), user_seismic_data)
    calculator = Calculator(user_values)
    validator = SeismicAnchorValidator(calculator)
    validation_result = validator.validate(calculator.panels)

    subarrays = calculator.subarray_summary()
    subarray_data = []
    for subarray in subarrays:
        data = {
            "subarray": subarray.subarray_number,
            "required_seismic_anchors": subarray.required_seismic_anchors,
            "weight": round(subarray.weight),
        }
        subarray_data.append(data)

    if not validation_result:
        session_manager.save_user_provided_seismic_anchors(user_seismic_data)
        panel_data = ProjectPresenter(user_values.system_type(), user_values.module_type()).get_panel_data(calculator.get_computed_csv_columns(),
                                                                                                           calculator.subarrays)
        db_session.close()
        return jsonify({
            "status": "success",
            "error": None,
            "panel_data": panel_data,
            "subarray_data": subarray_data
        })
    else:
        db_session.close()
        return jsonify({
            "status": "error",
            "error": validation_result.value,
            "panel_data": None,
            "subarray_data": subarray_data
        })
