import time
import settings
from sys import platform as sys_platform
from utils.utils_func import httpGetHandler
from PIL import Image
from io import BytesIO
import requests

if settings.IS_TEST:
    import piexif
    from PIL import Image
    import threading


class CaptureBasic():
    # program_sign = Signal(dict)0
    base_host = "http://localhost:5513"
    _get_image_index = 0
    _get_folder_index = 0
    is_first_init = 0

    def __init__(self):
        # self.window = window
        # 状态 1 进行中 2 已停止
        self.state = 2
        # 总拍照数量
        self.total_num = 0
        # 是否获取照片
        self.is_get_photo = False
        # self.keyboard = Controller()
        self.hwnd = None
    # def getPreviewImage(self)->Image:
    #     '''获取预览图'''
    #     yzmdata = requests.get(self.base_host + "/preview.jpg")
    #     tempIm = BytesIO(yzmdata.content)
    #     im = Image.open(tempIm)
    #     return im

    def auto_focus(self):
        # 执行拍照
        time.sleep(0.2)
        self.run_capture_action("LiveView_Focus")

    def getCaptureFolderPath(self):
        """获取预览图"""
        response = httpGetHandler(
            url=self.base_host,
            params={"slc": "get", "param1": "session.folder"},
            headers={},
            )
        return response.text

    def checkCameraConnect(self):
        """检查相机是否连接"""
        response = httpGetHandler(
            url=self.base_host,
            params={"slc": "get", "param1": "iso"},
            headers={},
        )
        if response.text == "未将对象引用设置到对象的实例。":
            return False
        return True

    def run_capture_action(self,command):
        '''执行capture动作'''
        response = httpGetHandler(url=self.base_host, params={"CMD":command},headers={})
        return response
    # def photograph(self):
    #     """
    #     Args:
    #         data:
    #         info_show: 信息输出
    #         image_deal_mode:0 表示左脚，1表示右脚
    #     Returns:
    #     """
    #     print("142----------------------------photograph")
    #     # 执行拍照
    #     if not self.hwnd:
    #         return False, {"flag": "{} 未打开".format(settings.CaptureSoftwareName)}
    #     if self.state == 1:
    #         print("当前有未完成的任务")
    #         return False, {"flag": "当前有未完成的任务"}
    #     print("开始拍照")
    #     self.state = 1
    #     if not self.set_foreground_window():
    #         return False, {"flag": "no {}".format(settings.CaptureSoftwareName)}
    #     time.sleep(0.1)
    #     # 自动对焦
    #     self.auto_focus()
    #     # self.send_win32_key(self.hwnd, key_1=win32con.VK_CONTROL, key_2=win32con.VK_F2)

    #     if settings.IS_TEST:
    #         # print("56-----测试拍照")
    #         threading.Thread(target=self.test_add_photo, args=()).start()
    #     # self.program_sign.emit({"type": "add_to_photo_todo_list",
    #     #                         "data": data})
    #     time.sleep(float(settings.PhotographSeconds))

    # def test_add_photo(self):
    #     def copy_file(srcfile, dstpath, dstfile):  # 复制函数
    #         if not os.path.isfile(srcfile):
    #             # print("%s not exist!" % (srcfile))
    #             return
    #         else:
    #             if int(os.path.getsize(srcfile) / 1024) < 10:
    #                 return
    #             # fpath, fname = os.path.split(srcfile)  # 分离文件名和路径
    #             if not os.path.exists(dstpath):
    #                 os.makedirs(dstpath)  # 创建路径
    #             shutil.copy(srcfile, dstfile)  # 复制文件

    #     print("模拟拍照  test_add_photo")
    #     time.sleep(0.9)
    #     s = time.time()
    #     source_path = r"{}\PhotoImageDir\test_source".format(os.getcwd())
    #     check_path(source_path)

    #     # 整理所有测试源照片
    #     images_path_list = []
    #     folder_list = get_folder(source_path)
    #     for folder_dict in folder_list:
    #         folder_path = folder_dict["folder_path"]
    #         _pics = [x["file_path"] for x in get_images(folder_path)]
    #         if _pics:
    #             images_path_list.append(_pics)

    #     if len(images_path_list) <= CaptureBasic._get_folder_index:
    #         CaptureBasic._get_folder_index = 0
    #         CaptureBasic._get_image_index = 0
    #     srcfile = images_path_list[CaptureBasic._get_folder_index][CaptureBasic._get_image_index]

    #     # 新文件夹
    #     CaptureBasic._get_image_index += 1
    #     if len(images_path_list[CaptureBasic._get_folder_index]) <= CaptureBasic._get_image_index:
    #         CaptureBasic._get_folder_index += 1
    #         CaptureBasic._get_image_index = 0

    #     # print("pic:", srcfile)
    #     e = os.path.splitext(os.path.split(srcfile)[1])[1]

    #     # 修改图片时间
    #     if e != ".CR2":
    #         _time = time.strftime("%Y:%m:%d %H:%M:%S", time.localtime(time.time()))
    #         exif_ifd = {piexif.ExifIFD.DateTimeOriginal: _time}
    #         exif_dict = {"Exif": exif_ifd}
    #         exif_bytes = piexif.dump(exif_dict)
    #         im = Image.open(srcfile)
    #         im.save(srcfile, exif=exif_bytes)

    #     dst_path = settings.PhotoOutputDir
    #     # dst_path = "{}/data".format(os.getcwd())
    #     e = os.path.splitext(srcfile)[-1]
    #     new_name = "~{}{}".format(int(time.time() * 10), e)
    #     dst_file = "{}/{}".format(dst_path, new_name)
    #     print("测试数据   dst_file", dst_file)
    #     copy_file(srcfile, dst_path, dst_file)
    #     # print("修改图片耗时：{}".format(time.time() - s))

    def last_images(self):
        if not self.hwnd:
            return
        # win32gui.SetForegroundWindow(self.hwnd)
        # self.keyboard.press(Key.ctrl)
        # self.keyboard.press(Key.left)
        # self.keyboard.release(Key.left)
        # self.keyboard.release(Key.ctrl)

    def next_images(self):
        # 执行拍照
        if not self.hwnd:
            return
        # win32gui.SetForegroundWindow(self.hwnd)
        # self.keyboard.press(Key.ctrl)
        # self.keyboard.press(Key.right)
        # self.keyboard.release(Key.right)
        # self.keyboard.release(Key.ctrl)

    def test_1(self):
        if not self.hwnd:
            return
        # 执行照片全选与导出
        # win32gui.SetForegroundWindow(self.hwnd)
        # self.keyboard.press(Key.ctrl)
        # self.keyboard.press("a")
        # self.keyboard.release("a")
        # self.keyboard.release(Key.ctrl)
        # time.sleep(1)
        # # 照片导出
        # self.keyboard.press(Key.ctrl)
        # self.keyboard.press("d")
        # self.keyboard.release("d")
        # self.keyboard.release(Key.ctrl)
if __name__ == "__main__":
    cap = CaptureBasic()
    # cap.auto_focus()
    # cap.auto_focus()
    # cap.run_capture_action("Capture")
    camera_conn = cap.checkCameraConnect()
    print("cccc", camera_conn)
