import logging
import os
from common.status import HTTP_200_OK, HTTP_500_INTERNAL_SERVER_ERROR
from flask import Blueprint
from flask_jwt_extended import jwt_required
from median.views import RawConfig
from median.models import Label, Product
from median.database import mysql_db

from ressources.blueprint.config.config_service import DrugStandard

logger = logging.getLogger("median")

DRUGS_MAPPING = {
    "fr": {
        "country": "de",
        "standard": DrugStandard.Ucd.value,
        "ucd_name": "UCD",
        "cip_name": "CIP",
        "cip_standard": "gs1",
    },
    "de": {
        "country": "de",
        "standard": DrugStandard.Pzn.value,
        "ucd_name": "PZN8",
        "cip_name": "PZN13",
        "cip_standard": "gs1",
    },
    "be": {
        "country": "be",
        "standard": DrugStandard.Cnk.value,
        "ucd_name": "CNK",
        "cip_name": "GTIN",
        "cip_standard": "gs1",
    },
}


config_blueprint = Blueprint("config", __name__)


@config_blueprint.route("reappro", methods=["GET"])
@jwt_required()
def get_reappro_config_values():
    reappro_props = ["k_eco_superviseur", "k_annule_remplace"]

    try:
        data = {}
        for prop in reappro_props:
            config = RawConfig().read(prop)
            if config is None:
                logger.error(f"Config - Reappro : {config.propriete} not found")
            elif config.value == "":
                logger.error(f"Config - Reappro : {config.propriete} is empty")
            else:
                data[config.propriete] = config.value

        return data, HTTP_200_OK

    except Exception as e:
        logger.error(str(e))
        return {"error": str(e)}, HTTP_500_INTERNAL_SERVER_ERROR


@config_blueprint.route("drugs", methods=["GET"])
@jwt_required()
def get_drug_config():
    """
    Retrieve the drugs system associate to the Median installation country
    """
    config = RawConfig().read("k_drug_country")

    if config is None:
        obj = None
    else:
        try:
            obj = DRUGS_MAPPING[config.value]
        except KeyError:
            obj = None

    # Retrieve the free fields

    return {"data": obj, "fields": drugs_free_fields()}, HTTP_200_OK


def drugs_free_fields():
    """
    Retrieve all free fields for drugs form
    """
    res = {}
    freelabels = Label.select(Label).where((Label.code.startswith("ref_")) & (Label.readonly < 2)).order_by(Label.code)
    for custom in freelabels:
        fieldName = custom.code.replace("ref_", "x_")
        res[fieldName] = {
            "name": custom.libelle,
            "code": custom.code,
            "readonly": custom.readonly,
            "api": custom.libelle_0,
            "params": custom.libelle_1,
            "maxsize": get_field_size(Product._meta.table_name, fieldName),
        }
    return res


def get_field_size(table_name, field_name):
    """
    Get the data max size for a given field from information schema
    """
    try:
        query = """
            SELECT CHARACTER_MAXIMUM_LENGTH
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE TABLE_NAME = %s
            AND COLUMN_NAME = %s
        """
        cursor = mysql_db.execute_sql(
            query,
            (
                table_name,
                field_name,
            ),
        )
        result = cursor.fetchone()
        return result[0] if result else 0
    except Exception:
        return 0


@config_blueprint.route("/server-config", methods=["GET"])
def get_server_config():
    # Base return objects
    mqttMode = False

    serverMode = {
        # Used for the mode overlay
        "active": os.environ.get("SERVER_MODE", "0"),
        "text": os.environ.get("SERVER_MODE_TEXT", ""),
        "color": os.environ.get("SERVER_MODE_COLOR", ""),
    }

    return {"serverMode": serverMode, "mqttMode": mqttMode}, HTTP_200_OK
