#!D:\IDE\Anaconda3\envs\Microscope_Scan python
# -*- coding: UTF-8 -*-
"""
@FileName   : ImageAnalysisModel.py
@Account    : Administrator
@Time       : 2025/8/15 11:56
@Author     : xsh
@Description:
"""
from PyQt5 import Qt
from datetime import datetime, date
import copy
from AppCore.AppDBModels.CoreModel import (CoreModel, DBManager, dbController)
from sqlalchemy.orm import declarative_base, mapper, sessionmaker, Session
from sqlalchemy.orm import (declarative_base, Mapped, mapped_column, relationship, mapper, sessionmaker)
from sqlalchemy import Table, Engine, create_engine, Column, ForeignKey, and_, or_, insert, delete, update, select, func, ColumnElement,distinct
from sqlalchemy.types import (Text, VARCHAR, REAL, Float, Integer, String, SmallInteger, DateTime, Date, ARRAY,Boolean, JSON)
from sqlalchemy.orm.decl_api import DeclarativeBase, MetaData
from AppUtils.utils import *
from AppCore.Levels import *

class ImageAnalysisModel(CoreModel):
    __tablename__ = 't_ImageAnalysisModel'
    ID                  : Mapped[int    ] = mapped_column(primary_key=True     , nullable=False)
    contrast_weight     : Mapped[float  ] = mapped_column(      default=1.0          , nullable=True , doc='', comment='')
    saturation_weight   : Mapped[float  ] = mapped_column(      default=1.0          , nullable=True , doc='', comment='')
    exposure_weight     : Mapped[float  ] = mapped_column(      default=1.0          , nullable=True , doc='', comment='')
    best_illumination   : Mapped[float  ] = mapped_column(      default=0.5          , nullable=True , doc='', comment='')
    best_sigma          : Mapped[float  ] = mapped_column(      default=0.2          , nullable=True , doc='', comment='')
    analysis_weight     : Mapped[float  ] = mapped_column(      default=0.95         , nullable=True , doc='', comment='')
    layers_num          : Mapped[int    ] = mapped_column(      default=5            , nullable=True , doc='', comment='')
    analysis_ksize      : Mapped[int    ] = mapped_column(      default=11           , nullable=True , doc='', comment='')
    analysis_sigma      : Mapped[int    ] = mapped_column(      default=5            , nullable=True , doc='', comment='')
    analysis_radius     : Mapped[int    ] = mapped_column(      default=64           , nullable=True , doc='', comment='')
    isAnalysis          : Mapped[int    ] = mapped_column(      default=0            , nullable=True , doc='融合图像优化', comment='融合图像优化')
    isGaussi            : Mapped[int    ] = mapped_column(      default=0            , nullable=True , doc='图像融合方式', comment='图像融合方式')
    isBigAnalysis       : Mapped[int    ] = mapped_column(      default=0            , nullable=True , doc='大图优化标志', comment='大图优化标志')
    isIntegration       : Mapped[int    ] = mapped_column(      default=0            , nullable=True , doc='图像融合标志', comment='图像融合标志')
    isFocusingHDR       : Mapped[int    ] = mapped_column(      default=0            , nullable=True , doc='图像预处理　', comment='图像预处理　')
    isCameraHDR         : Mapped[int    ] = mapped_column(      default=0            , nullable=True , doc='图像预处理　', comment='图像预处理　')
    Information         : Mapped[str    ] = mapped_column(Text, default='Aberration' , nullable=True , doc='说明信息　', comment='说明信息　') # 说明信息　
    name                : Mapped[str    ] = mapped_column(Text, default='Aberration' , nullable=True , doc='分类模型　', comment='分类模型　') # 分类模型　

    def __init__(self, **args):
        super(ImageAnalysisModel, self).__init__()
        self.initialize()
        self.initParameter(**args)

    def initValue(self):
        super(ImageAnalysisModel, self).initValue()

        self.ID                  = 1            #
        self.contrast_weight     = 1.0          #
        self.saturation_weight   = 1.0          #
        self.exposure_weight     = 1.0          #
        self.best_illumination   = 0.5          #
        self.best_sigma          = 0.2          #
        self.layers_num          = 5            #
        self.analysis_ksize      = 11           #
        self.analysis_sigma      = 5            #
        self.analysis_radius     = 64           #
        self.analysis_weight     = 0.95         #
        self.isAnalysis          = 0            #
        self.isGaussi            = 0            #
        self.isBigAnalysis       = 0            #
        self.isIntegration       = 0            #
        self.isFocusingHDR       = 0            #
        self.isCameraHDR         = 0            #
        self.Information         = 'Aberration' #
        self.name                = 'Aberration' #


    @property
    def is_focusing_hdr(self):
        return not self.is_camera_hdr and not self.isIntegration

    @property
    def is_camera_hdr(self):
        return self.hasCameraHDR and self.isCameraHDR

    @property
    def is_integration(self):
        return self.hasIntegration and self.isIntegration


    @classmethod
    def default_config(cls):
        result: cls = cls.__new__(cls)
        result.__init__()
        result.initValue()
        return result

    @classmethod
    def initModels(cls):
        return [
            cls.instance(ID                  = 1   , Information         = 'Aberration'    , name                = 'Aberration'    , contrast_weight     = 1.0 ,saturation_weight   = 1.0 ,exposure_weight     = 1.0 ,best_illumination   = 0.5 ,best_sigma          = 0.2 ,layers_num          = 5   ,analysis_ksize      = 11  ,analysis_sigma      = 5   , analysis_radius     = 64, analysis_weight=0.95, isFocusingHDR=0, isCameraHDR=0),
            cls.instance(ID                  = 2   , Information         = 'Karyotyping'   , name                = 'Karyotyping'   , contrast_weight     = 1.0 ,saturation_weight   = 1.0 ,exposure_weight     = 1.0 ,best_illumination   = 0.5 ,best_sigma          = 0.2 ,layers_num          = 5   ,analysis_ksize      = 11  ,analysis_sigma      = 5   , analysis_radius     = 64, analysis_weight=0.95, isFocusingHDR=0, isCameraHDR=0),
            cls.instance(ID                  = 3   , Information         = 'Micronucleus'  , name                = 'Micronucleus'  , contrast_weight     = 1.0 ,saturation_weight   = 1.0 ,exposure_weight     = 1.0 ,best_illumination   = 0.5 ,best_sigma          = 0.2 ,layers_num          = 5   ,analysis_ksize      = 15  ,analysis_sigma      = 5   , analysis_radius     = 64, analysis_weight=0.95, isFocusingHDR=0, isCameraHDR=0),
        ]

    @classmethod
    def getConfig(cls, name: str):
        item: cls = cls.instance()
        try:
            dbController.initEngine()
            with Session(dbController.Engine) as session:
                try:
                    pattern: str = f'{name}%'
                    item = session.query(cls).filter(cls.name.like(pattern)).first()
                except Exception as e:
                    AppUtils.print_Exception(e)
        except Exception as EX:
            AppUtils.print_Exception(EX)
        return item

    @classmethod
    def AnalysisParameter(cls, name: str):
        item: cls = cls.instance()
        try:
            dbController.initEngine()
            with Session(dbController.Engine) as session:
                try:
                    pattern: str = f'{name}%'
                    item = session.query(cls).filter(cls.name.like(pattern)).first()
                except Exception as e:
                    AppUtils.print_Exception(e)
        except Exception as EX:
            AppUtils.print_Exception(EX)
        return item

    @classmethod
    def IntegrationParameter(cls) -> (float, float, float, float, float, float):
        contrast_weight     : float
        saturation_weight   : float
        exposure_weight     : float
        best_illumination   : float
        best_sigma          : float
        layers_num          : int

        model: cls = cls.getMaxPrimaryItem()
        if model is None:
            model = cls.default_config()
        contrast_weight     = model.contrast_weight
        saturation_weight   = model.saturation_weight
        exposure_weight     = model.exposure_weight
        best_illumination   = model.best_illumination
        best_sigma          = model.best_sigma
        layers_num          = model.layers_num
        return contrast_weight   ,saturation_weight ,exposure_weight   ,best_illumination ,best_sigma        ,layers_num

    @classmethod
    def AnalysisParameter(cls) -> (int, int, int, float):
        analysis_ksize      : int       #
        analysis_sigma      : int       #
        analysis_radius     : int       #
        analysis_weight     : float     #
        model: cls = cls.getMaxPrimaryItem()
        if model is None:
            model = cls.default_config()
        analysis_ksize   = model.analysis_ksize
        analysis_sigma   = model.analysis_sigma
        analysis_radius  = model.analysis_radius
        analysis_weight  = model.analysis_weight
        return analysis_ksize , analysis_sigma , analysis_radius, analysis_weight




    @property
    def hasIntegration (self) -> bool:
        return hasattr(self, 'isIntegration' ) and isinstance(self.isIntegration, (bool, int))

    @property
    def hasFocusingHDR (self) -> bool:
        return hasattr(self, 'isFocusingHDR' ) and isinstance(self.isFocusingHDR, (bool, int))

    @property
    def hasCameraHDR   (self) -> bool:
        return hasattr(self, 'isCameraHDR'   ) and isinstance(self.isCameraHDR  , (bool, int))




    @property
    def hasAnalysis    (self) -> bool:
        return hasattr(self, 'isAnalysis'    ) and isinstance(self.isAnalysis    , (bool, int))

    @property
    def hasGaussi      (self) -> bool:
        return hasattr(self, 'isGaussi'      ) and isinstance(self.isGaussi      , (bool, int))

    @property
    def hasBigAnalysis (self) -> bool:
        return hasattr(self, 'isBigAnalysis' ) and isinstance(self.isBigAnalysis , (bool, int))















    __field__ = (
        'ID'                  ,
        'contrast_weight'     ,
        'saturation_weight'   ,
        'exposure_weight'     ,
        'best_illumination'   ,
        'best_sigma'          ,
        'analysis_weight'     ,
        'layers_num'          ,
        'analysis_ksize'      ,
        'analysis_sigma'      ,
        'analysis_radius'     ,
        'isAnalysis'          ,
        'isGaussi'            ,
        'isBigAnalysis'       ,
        'isIntegration'       ,
        'isFocusingHDR'       ,
        'isCameraHDR'         ,
        'Information'         ,
        'name'                ,
    )

    __types__ = (
        int    ,
        float  ,
        float  ,
        float  ,
        float  ,
        float  ,
        float  ,
        int    ,
        int    ,
        int    ,
        int    ,
        int    ,
        int    ,
        int    ,
        int    ,
        int    ,
        int    ,
        str    ,
        str    ,
    )