# coding=utf-8
import json
import logging
import time

import pyautogui
import mss
import requests
from easy_use_tools.utils.common import base

class ScreenshotsEntity:
    def __init__(self,monitor_id=-1,upload_img=False):
        self.monitor_id = monitor_id
        self.upload_img = upload_img


    def _prepare(self):
        """
        @Description: 准备参数
        """
        pass
    def get(self,save_path='/tmp/screenshots_save.png'):
        """
            @Description: 截图并保存为文件
        """
        if self.monitor_id <0:
            logging.info("[ScreenshotsEntity][]保存默认单个显示器截图")
            screenshot = pyautogui.screenshot()
            screenshot.save(save_path)
        else:
            with mss.mss() as sct:
                # 获取所有屏幕合成的整张图
                logging.info(f"[ScreenshotsEntity]保存指定显示器[{self.monitor_id}]截图")
                img = sct.grab(sct.monitors[0])  # [0] 表示虚拟桌面即将多个显示器截图合并成一张，[1]为第一台显示器截图，[2]为第二台显示器截图
                mss.tools.to_png(img.rgb, img.size, output=save_path)
        return save_path

    def check(self,img_path=None):

        """
            @Description:检测图像质量
        """
        # 目标 URL
        conf_data = base.get_config_data()
        url = f"http://{conf_data['img_server']['api_ip']}:{conf_data['img_server']['api_port']}/{conf_data['img_server']['api_check_path']}"
        print(f"图片质量检测url:{url}")
        if img_path:
            logging.info("检测图片路径:{}")
        else:
            img_path = self.get()
            logging.info("图片地址未给,截屏一次检测:")
        # 打开图片并以二进制形式发送
        with open(img_path, 'rb') as f:
            files = {'image': ('test.png', f, 'image/jpeg')}  # 字段名、文件名、MIME类型
            response = requests.post(url, files=files)

        rst_code = response.status_code
        if rst_code == 200:
            rst_info = response.text  # {"code":200,"data":{"result":{"predicted_class":1}},"status":"Operation Success"}
            logging.info(f"server return info: {rst_info}")
            rst_dict = json.loads(rst_info)
            if rst_dict.get("data").get("result").get("predicted_class") == 1:
                logging.info("image check pass")
                if self.upload_img:
                    base.send_check_img(img_path, "normal")
                return True
            else:
                logging.error("image check failed")
                if self.upload_img:
                    base.send_check_img(img_path, "normal")
                return False
        else:
            logging.error(f"[{rst_code}]server return code error")
            return False

    def loop_check(self,time_gap,img_path=None):
        """
            @Description:循环检测图像质量
        """
        while True:
            rst=self.check(img_path)
            if rst:
                print("图片检测结果:通过,将会sleep {time_gap}s后进行下一次检测")
                time.sleep(time_gap)
            else:
                print("图片检测结果:失败,将会sleep {time_gap}s后进行下一次检测")
                return False
