# -*- coding:utf-8 -*-
from ssat_sdk import getMenuTree3SelectedPExcelPath

from ssat_sdk.picture.RGB import RGBColor
from ssat_sdk.picture.color_space import CIEluvCaculator
from ssat_sdk.picture.feature_detect import FeatureDetect
from ssat_sdk.picture.image_util import *

import os
import sys
import time
import numpy as np
import cv2 as cv
import json
from ssat_sdk.MenuTree3.TConfig import TConfig
from ssat_sdk.MenuTree3.TExcelParser import CExcelParser

g_level = ['First', 'Second', 'Third', 'Fourth', 'Fifth', 'Sixth',
           'Seventh', 'Eighth', 'Ninth', 'Tenth', 'Eleventh', 'Twelfth']


class TFocus():
    def __init__(self, project_path, uitRunner=None, screen=[1920, 1080], icon_shape=[1920, 1080]):
        self.params_path = project_path
        self.rgbColor = RGBColor()
        self.CIE = CIEluvCaculator()
        self.feature_detect = FeatureDetect()
        self.xlsparser = uitRunner.uitPathManage
        # icon分辨率width*height;
        self.icon_shape = icon_shape
        # 当前屏幕分辨率;
        self.screen = screen
        # 比率;
        self.rate = self.icon_shape[0] / self.screen[0]

    def findFocusByIcon(self, src_pic, icon_pic,
                        dcfg={"offset": 20, "minPeri": 0, "maxPeri": 0, "minArea": 0, "maxArea": 0, "morphology": []}):
        iconImg = cv.imread(icon_pic)
        # 获取小图平均bgr值;
        bgr = self.rgbColor.getAvgBGR(iconImg)
        print "findFocusByIcon,bgr:%s, src_pic=%s, icon_pic=%s, dcfg=%s" % (
            str(bgr), src_pic, icon_pic, str(dcfg))
        if dcfg.has_key("morphology"):
            morphology = dcfg["morphology"]
        else:
            morphology = []
        return self.feature_detect.findCurrentFoucsByColor(
            src_pic,
            [],
            bgr,
            dcfg["offset"],
            dcfg["minPeri"],
            dcfg["maxPeri"],
            dcfg["minArea"],
            dcfg["maxArea"],
            morphology)

    # 文本颜色焦点区域查找;
    def findFramelessBoxByIcon(self, src_pic, icon_pic, offset=20):
        iconImg = cv.imread(icon_pic)
        # 获取小图平均bgr值;
        bgr = self.rgbColor.getAvgBGR(iconImg)
        print "findFramelessBoxByIcon,bgr:%s, src_pic=%s, icon_pic=%s, offset=%s" % (
            str(bgr), src_pic, icon_pic, str(offset))
        return self.feature_detect.findFramelessFocusByColor(src_pic, [], bgr, offset)

    '''
        在传入的图片上,查找指定小图片bgr颜色框矩形区域,返回矩形区域的坐标
        :param bigPic:图片路径
        :param level:excel层次
        :param first_parent:大部分情况下是根菜单;少部分情况是当前option的parent;
        :return rectArea:矩形区域和区域图像内容
        '''

    def findRectByIcon(self, bigPic, level, first_parent, option=""):
        print "level:", level
        print "first_parent:", first_parent
        if option.__len__() == 0:
            icon_path = os.path.join(self.params_path, "icon\\", str(
                first_parent) + "." + str(level) + ".png")
        else:
            icon_path = os.path.join(self.params_path, "icon\\", str(
                first_parent) + "." + str(level) + "_" + option + ".png")
        print "icon_path_option=", icon_path
        if os.path.exists(icon_path) is False:
            icon_path = os.path.join(self.params_path, "icon\\", str(
                first_parent) + "." + str(level) + ".png")
            print "icon_path=", icon_path
            if os.path.exists(icon_path) is False:
                icon_path = os.path.join(self.params_path, "icon\\", str(
                    first_parent) + "." + str('First') + ".png")
                print "icon_path_First=", icon_path
                if os.path.exists(icon_path) is False:
                    return False, []
        # 获取配置文件值;
        dcfg = {"offset": 20, "minPeri": 0,
                "maxPeri": 0, "minArea": 0, "maxArea": 0}
        ini_path = os.path.join(self.params_path, "menutree.ini")
        if os.path.exists(ini_path) is True:
            tconfig = TConfig(ini_path)
            if tconfig.has_option(level, first_parent):
                dcfg = tconfig.get_dict(tconfig.get_value(level, first_parent))

        dcfg['minPeri'] = self.rate * dcfg['minPeri']
        dcfg['maxPeri'] = self.rate * dcfg['maxPeri']
        dcfg['minArea'] = pow(self.rate, 2) * dcfg['minArea']
        dcfg['maxArea'] = pow(self.rate, 2) * dcfg['maxArea']
        if "morphology" not in dcfg:
            dcfg["morphology"] = []
        return self.findFocusByIcon(bigPic, icon_path, dcfg)

    '''
    获取option配置信息;
    '''

    def getOptionConfig(self, cur_option, is_value_sheet=False):
        # 获取Option的others字段信息;
        if self.xlsparser is None:
            self.xlsparser = CExcelParser(getMenuTree3SelectedPExcelPath())
            # 读取excel并解析出内容;
            self.xlsparser.read_excel()
        # 获取option的路径表;
        pp = self.xlsparser.get_option_paths(cur_option)
        if pp.__len__() == 0:
            print 'getOptionConfig.get_option_paths(%s) is null' % (cur_option)
            return False, {"icon_path": "", "dcfg": {}, "dir_path": ""}

        # 获取first_parent;
        first_parent = pp[g_level[0]]['parent']
        # 当前option所在level;
        cur_level = g_level[pp.__len__() - 1]
        # 当前父路径;
        cur_parent = pp[cur_level]['parent']
        if is_value_sheet is True:
            cur_level = 'value'
        # print first_parent, cur_level, cur_parent, cur_option

        # 获取配置文件值;
        dcfg = {}
        ini_path = os.path.join(self.params_path, "menutree.ini")
        tconfig = TConfig(ini_path)
        # 首先找当前路径图;
        icon_path = os.path.join(self.params_path, "icon\\", str(
            cur_parent) + "." + str(cur_level) + "_" + cur_option + ".png")
        icon_dir_path = os.path.join(self.params_path, "icon\\", str(
            cur_parent) + "." + str(cur_level) + "_" + cur_option + ".dir.png")
        dcfg = tconfig.get_value_dict(cur_level, cur_parent + '.' + cur_option)
        print u"trying icon:%s"%icon_path
        print u"trying dcfg:get_value_dict(%s, %s)"%(cur_level, cur_parent + '.' + cur_option)
        # icon路径;
        if os.path.exists(icon_path) is False:
            print u'图标优先级0:[cur_parent].[cur_level]_[cur_option].png=%s is null' % (
                icon_path)
            # 当前次路径图;
            icon_path = os.path.join(self.params_path, "icon\\", str(
                cur_parent) + "." + str(cur_level) + ".png")
            icon_dir_path = os.path.join(self.params_path, "icon\\", str(
                cur_parent) + "." + str(cur_level) + ".dir.png")
            dcfg = tconfig.get_value_dict(cur_level, cur_parent)
            print u"trying icon:%s" % icon_path
            print u"trying dcfg:get_value_dict(%s, %s)" % (cur_level, cur_parent)
            if os.path.exists(icon_path) is False:
                print u'图标优先级1:[cur_parent].[cur_level].png=%s is null' % (
                    icon_path)
                # first层;
                icon_path = os.path.join(self.params_path, "icon\\", str(
                    first_parent) + "." + str(cur_level) + "_" + cur_option + ".png")
                icon_dir_path = os.path.join(self.params_path, "icon\\", str(
                    first_parent) + "." + str(cur_level) + "_" + cur_option + ".dir.png")
                dcfg = tconfig.get_value_dict(
                    cur_level, first_parent + '.' + cur_option)
                print u"trying icon:%s" % icon_path
                print u"trying dcfg:get_value_dict(%s, %s)" % (cur_level, first_parent + '.' + cur_option)
                if os.path.exists(icon_path) is False:
                    print u'图标优先级2:[first_parent].[cur_level]_[cur_option].png=%s is null' % (
                        icon_path)
                    # first层次路径图;
                    icon_path = os.path.join(self.params_path, "icon\\", str(
                        first_parent) + "." + str(cur_level) + ".png")
                    icon_dir_path = os.path.join(self.params_path, "icon\\", str(
                        first_parent) + "." + str(cur_level) + ".dir.png")
                    dcfg = tconfig.get_value_dict(cur_level, first_parent)
                    print u"trying icon:%s" % icon_path
                    print u"trying dcfg:get_value_dict(%s, %s)" % (cur_level, first_parent)
                    if os.path.exists(icon_path) is False:
                        print u'图标优先级3:[first_parent].[cur_level].png =%s is null' % (
                            icon_path)
                # endif;
            # endif;
        # endif;

        if dcfg.__len__() == 0:
            dcfg = {"offset": 20, "minPeri": 0,
                    "maxPeri": 0, "minArea": 0, "maxArea": 0, "morphology": []}
            print u"get dcfg fail!Using default para!"

        if os.path.exists(icon_path) is False:
            print 'getOptionConfig:current use icon_path=%s is null' % (
                icon_path)
            return False, {"icon_path": "", "dcfg": {}, "dir_path": ""}
        print u"实际使用的icon图片路径icon_path:%s, 实际使用INI配置:%s" % (
            str(icon_path), str(dcfg))

        # 返回路径;
        return True, {"icon_path": icon_path, "dcfg": dcfg, "dir_path": icon_dir_path}

    def findRectByIcon2(self, src_pic, cur_option, is_value_sheet=False):
        # 获取参数;
        result, opcfg = self.getOptionConfig(cur_option, is_value_sheet)
        if result is False:
            return False, []

        icon_path = opcfg['icon_path']
        dcfg = opcfg['dcfg']
        dcfg['minPeri'] = self.rate * dcfg['minPeri']
        dcfg['maxPeri'] = self.rate * dcfg['maxPeri']
        dcfg['minArea'] = pow(self.rate, 2) * dcfg['minArea']
        dcfg['maxArea'] = pow(self.rate, 2) * dcfg['maxArea']
        print u"实际使用的聚焦参数字典dcfg:%s" % str(dcfg)
        if "morphology" not in dcfg:
            dcfg["morphology"] = []

        return self.findFocusByIcon(src_pic, icon_path, dcfg)


def rgb2hsv(r, g, b):
    r, g, b = r / 255.0, g / 255.0, b / 255.0
    mx = max(r, g, b)
    mn = min(r, g, b)
    df = mx - mn
    # h值
    if mx == mn:
        h = 0
    elif mx == r and g >= b:
        h = (60 * (g - b) / df) % 360
    elif mx == r and g < b:
        h = (60 * ((g - b) / df) + 360) % 360
    elif mx == g:
        h = (60 * ((b - r) / df) + 120) % 360
    elif mx == b:
        h = (60 * ((r - g) / df) + 240) % 360
    # s值
    if mx == 0:
        s = 0
    else:
        s = df / mx * 255
    # v值
    v = mx * 255
    # 返回;
    return h, s, v


if __name__ == "__main__":
    # print '\n\n====>\n', pow(10, 2)
    tFocus = TFocus(r"D:\SAT\resource\MenuTree\MS6586\ISDB")
    tFocus.getOptionConfig('backlight', True)
    tFocus.findRectByIcon2('', 'backlight')  # lock
    if 0:
        bigPic_2 = r"D:\CH01.JPG"
        icon = r"D:\SAT\resource\MenuTree\mi\AM950_IND_V27N\result.png"
        result, contourRect = tFocus.findRectByIcon(bigPic_2, 'Third', 'lock')
        print "__name__,rect:", result, contourRect
        if result is True:
            saveCropPic(bigPic_2, icon, contourRect)