#!D:/IDE/anaconda3/envs/Microscope_Scan python
# -*- coding: UTF-8 -*-
"""
@FileName：ProcessManager.py
@Description：
@Author：XSH
@Time：2025/11/19 10:13
@Department：研发部
@Copyright：©2025 乐辰生物
"""
from PyQt5 import Qt
import cv2
import numpy as np
from AppUtils.utils                     import *
from AppCore.Requests import *
from AppUtils.AppDBUtils                import AppDBUtils
from AppCore.DBModels                   import CellModel
def ImageSaveProcess(filename: str, image: np.ndarray):
    _info: Qt.QFileInfo
    _info = Qt.QFileInfo(filename)
    try:
        if not isinstance(image, np.ndarray) or len(_info.absoluteFilePath()) <= 0:
            return
        if not _info.dir().exists():
            _info.dir().mkpath(_info.absolutePath())
        cv2.imwrite(_info.absoluteFilePath(), image)
    except Exception as e:
        AppUtils.print_Exception(e)
    # print(filename)
    return


def SaveImagesProcess(buffer: dict[str, object]):
    if not isinstance(buffer, dict):
        return
    filename: str
    image   : np.ndarray
    _info   : Qt.QFileInfo
    for filename, image in buffer.items():
        if isinstance(filename, str) and isinstance(image, np.ndarray):
            _info = Qt.QFileInfo(filename)
            # print(_info.absoluteFilePath())
            try:
                if not isinstance(image, np.ndarray) or len(_info.absoluteFilePath()) <= 0:
                    return
                if not _info.dir().exists():
                    _info.dir().mkpath(_info.absolutePath())
                cv2.imwrite(_info.absoluteFilePath(), image)
            except Exception as e:
                AppUtils.print_Exception(e)
                try:
                    img: Qt.QImage = ImageUtils.cv2_to_QImage(image, -1, -1)
                    if img is not None and not img.isNull():
                        img.save(_info.absoluteFilePath(), _info.suffix())
                except Exception as qe:
                    AppUtils.print_Exception(qe)

    return


def QImageSaveProcess(filename: str, fmt: str, image: Qt.QImage):
    _info: Qt.QFileInfo
    _info = Qt.QFileInfo(filename)
    try:

        if image.isNull() or len(_info.absoluteFilePath()) <= 0:
            return
        # print(_info.absoluteFilePath())
        if not _info.dir().exists():
            _info.dir().mkpath(_info.absolutePath())
        image.save(_info.absoluteFilePath(), fmt)
    except Exception as e:
        AppUtils.print_Exception(e)


def TextSaveProcess(file_path: str, buffer: str):
    """将字符串保存到本地文件"""
    try:
        info: Qt.QFileInfo = Qt.QFileInfo(file_path)
        # print(info.absoluteFilePath())
        if len(info.absoluteFilePath()) <= 0:
            return
        if not info.dir().exists():
            info.dir().mkpath(info.absolutePath())
        file = Qt.QFile(info.absoluteFilePath())
        if file.open(Qt.QIODevice.WriteOnly | Qt.QIODevice.Text):
            out = Qt.QTextStream(file)
            out.setCodec('UTF-8')
            out << buffer
            out.flush()
            file.close()
            return True
        else:
            return False
    except Exception as e:
        AppUtils.print_Exception(e)
        return False

def TextAppendProcess(file_path: str, buffer: str):
    """将字符串保存到本地文件"""
    try:
        info: Qt.QFileInfo = Qt.QFileInfo(file_path)
        if len(info.absoluteFilePath()) <= 0:
            return
        if not info.dir().exists():
            info.dir().mkpath(info.absolutePath())
        file = Qt.QFile(info.absoluteFilePath())
        if file.open(Qt.QIODevice.Append | Qt.QIODevice.Text):
            out = Qt.QTextStream(file)
            out.setCodec('UTF-8')
            out << f'{buffer} \n'
            out.flush()
            file.close()
            return True
        else:
            return False
    except Exception as e:
        AppUtils.print_Exception(e)
        return False


def SaveSpecimenContext(chamber_number: int, row_number: int):
    from AppContexts.SpecimenContext import SpecimenContext
    from AppCore.AppDBModels.DBModels import SpecimenCountModel, ChamberStatusModel
    try:
        filename    : str
        SpecimenHead: str
        SpecimenInfo: str
        info        : Qt.QFileInfo
        Specimen    : SpecimenContext
        model       : ChamberStatusModel
        item: SpecimenCountModel = SpecimenCountModel.getSpecimen(chamber_number, row_number)
        if isinstance(item, SpecimenCountModel):
            Specimen    = SpecimenContext()
            model       = ChamberStatusModel.getChamberSlide(chamber_number, row_number)
            Specimen.as_field(item.to_field())
            Specimen.StartScanningDateTime  = model.CreateTime
            Specimen.StopScanningDateTime   = Qt.QDateTime.currentDateTime().toPyDateTime()
            filename, _ = AppDBUtils.text_filename(model)
            info: Qt.QFileInfo = Qt.QFileInfo(filename)
            SpecimenInfo = Specimen.toTEXT()
            if not info.dir().exists():
                info.dir().mkpath(info.absolutePath())
            file = Qt.QFile(info.absoluteFilePath())
            isOpened: bool
            isCreate = not info.exists()
            if isCreate:
                isOpened = file.open(Qt.QIODevice.WriteOnly | Qt.QIODevice.Text)
            else:
                isOpened = file.open(Qt.QIODevice.Append | Qt.QIODevice.Text)
            if not isOpened:
                return
            out = Qt.QTextStream(file)
            out.setCodec('UTF-8')
            if isCreate:
                SpecimenHead = Specimen.toHEADER()
                out << f'{SpecimenHead} \n'
            out << f'{SpecimenInfo} \n'
            out.flush()
            file.close()
    except Exception as e:
        AppUtils.print_Exception(e)



def TextReadProcess(file_path: str):
    """将字符串保存到本地文件"""
    buffer: str = ''
    try:
        info: Qt.QFileInfo = Qt.QFileInfo(file_path)
        if len(info.absoluteFilePath()) <= 0:
            return
            # print(info.absoluteFilePath())
        if not info.dir().exists():
            return info.dir().mkpath(info.absolutePath())
        file = Qt.QFile(info.absoluteFilePath())
        if file.open(Qt.QIODevice.WriteOnly | Qt.QIODevice.Text):
            out = Qt.QTextStream(file)
            out.setCodec('UTF-8')
            out.seek(0)
            while not out.atEnd():
                buffer += out.readLine()
            file.close()

    except Exception as e:
        AppUtils.print_Exception(e)
    return buffer


def AppendCellData(items: list[CellModel], images: list[np.ndarray]):
    from AppBackEnd.BackEndEventBus.WebSocketPool import WebSocketPool

    if isinstance(items, (list, tuple)) and isinstance(images, (tuple, list)):
        CellModel.append_all(items)
        WebSocketPool.GetInstance().SendEvent( Response.ImageList(buffer=images))

    pass
