from datetime import datetime

import sqlalchemy
from flask import Blueprint, render_template, Response, flash
from flask.typing import ResponseReturnValue
from flask_wtf import FlaskForm
from wtforms import IntegerField, BooleanField, SubmitField

from app.extensions import db
from app.models.mirrors import Country

bp = Blueprint("country", __name__)

_SECTION_TEMPLATE_VARS = {
    "section": "country",
    "help_url": "https://bypass.censorship.guide/user/countries.html"
}


@bp.app_template_filter("country_flag")
def filter_country_flag(country_code: str) -> str:
    country_code = country_code.upper()

    # Calculate the regional indicator symbol for each letter in the country code
    base = ord('\U0001F1E6') - ord('A')
    flag = ''.join([chr(ord(char) + base) for char in country_code])

    return flag


@bp.route('/list')
def country_list() -> ResponseReturnValue:
    countries = Country.query.filter(Country.destroyed.is_(None)).all()
    print(len(countries))
    return render_template("list.html.j2",
                           title="Countries",
                           item="country",
                           new_link=None,
                           items=sorted(countries, key=lambda x: x.country_code),
                           **_SECTION_TEMPLATE_VARS
                           )


class EditCountryForm(FlaskForm):  # type: ignore[misc]
    risk_level_override = BooleanField("Force Risk Level Override?")
    risk_level_override_number = IntegerField("Forced Risk Level", description="Number from 0 to 20", default=0)
    submit = SubmitField('Save Changes')


@bp.route('/edit/<country_id>', methods=['GET', 'POST'])
def country_edit(country_id: int) -> ResponseReturnValue:
    country = Country.query.filter(Country.id == country_id).first()
    if country is None:
        return Response(render_template("error.html.j2",
                                        section="country",
                                        header="404 Country Not Found",
                                        message="The requested country could not be found."),
                        status=404)
    form = EditCountryForm(risk_level_override=country.risk_level_override is not None,
                           risk_level_override_number=country.risk_level_override)
    if form.validate_on_submit():
        if form.risk_level_override.data:
            country.risk_level_override = form.risk_level_override_number.data
        else:
            country.risk_level_override = None
        country.updated = datetime.utcnow()
        try:
            db.session.commit()
            flash("Saved changes to country.", "success")
        except sqlalchemy.exc.SQLAlchemyError:
            flash("An error occurred saving the changes to the country.", "danger")
    return render_template("country.html.j2",
                           section="country",
                           country=country, form=form)
