import math

import cv2

from app.service.utils.decorator import ClassCallRunTime
from ..builder import PIPELINES


@PIPELINES.register_module()
class Scaling(object):
    def __init__(self):
        pass

    # @ClassCallRunTime
    def __call__(self, result):
        if result['keypoint'] in ['waistband', 'shoulder', 'head_point']:
            # milvus_db_keypoint_cache
            distance_clo = math.sqrt(
                (int(result['clothes_keypoint'][result['keypoint'] + '_left'][0]) - int(result['clothes_keypoint'][result['keypoint'] + '_right'][0])) ** 2
                +
                (int(result['clothes_keypoint'][result['keypoint'] + '_left'][1]) - int(result['clothes_keypoint'][result['keypoint'] + '_right'][1])) ** 2)

            distance_bdy = math.sqrt((int(result['body_point_test'][result['keypoint'] + '_left'][0]) - int(result['body_point_test'][result['keypoint'] + '_right'][0])) ** 2 + 1)
            # distance_clo = math.sqrt(
            #     (int(result['clothes_keypoint'][result['keypoint'] + '_left'].split("_")[0]) - int(result['clothes_keypoint'][result['keypoint'] + '_right'].split("_")[0])) ** 2
            #     +
            #     (int(result['clothes_keypoint'][result['keypoint'] + '_left'].split("_")[1]) - int(result['clothes_keypoint'][result['keypoint'] + '_right'].split("_")[1])) ** 2)
            #
            # distance_bdy = math.sqrt((int(result['body_point_test'][result['keypoint'] + '_left'][0]) - int(result['body_point_test'][result['keypoint'] + '_right'][0])) ** 2 + 1)
            if distance_clo == 0:
                result['scale'] = 1
            else:
                result['scale'] = distance_bdy / distance_clo
        elif result['keypoint'] == 'toe':
            distance_bdy = math.sqrt(
                (int(result['body_point_test']['foot_length'][0]) - int(result['body_point_test']['foot_length'][2])) ** 2
                +
                (int(result['body_point_test']['foot_length'][1]) - int(result['body_point_test']['foot_length'][3])) ** 2
            )

            Blur = cv2.GaussianBlur(result['gray'], (3, 3), 0)
            Edge = cv2.Canny(Blur, 10, 200)
            Edge = cv2.dilate(Edge, None)
            Edge = cv2.erode(Edge, None)
            Contour, _ = cv2.findContours(Edge, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
            Contours = sorted(Contour, key=cv2.contourArea, reverse=True)

            Max_contour = Contours[0]
            x, y, w, h = cv2.boundingRect(Max_contour)
            width = w
            distance_clo = width
            result['scale'] = distance_bdy / distance_clo
        elif result['keypoint'] == 'hand_point':
            result['scale'] = result['scale_bag']
        elif result['keypoint'] == 'ear_point':
            result['scale'] = result['scale_earrings']
        return result
