# -*- coding: utf-8 -*-
from django.core.files.base import ContentFile
from django.utils.crypto import get_random_string

from PIL import Image
from cStringIO import StringIO

from simulation.models import Mannequin
from simulation.custom_admin.functions import z_index_sort


# 이미지 합성기능 함수
# 남자 앞뒤 여자 앞뒤
# 자켓조끼둘다있으면 그것도 남자앞뒤 여자 앞뒤
# 최대 8번의 image_composite 기능 실행
def image_composite_controller(image_composite_parameters):
    fitting = image_composite_parameters['fitting']
    mannequin_id = image_composite_parameters['mannequin_id']
    fabric_index_list = image_composite_parameters['fabric_index_list']
    jacket_vest_on = image_composite_parameters['jacket_vest_on']

    only_jacket = False
    dummy_fabric_list = z_index_sort(fabric_index_list)
    dummy_off_jacket_fabric_list = z_index_sort(fabric_index_list)
    fabric_list = []
    off_jacket_fabric_list = []

    if jacket_vest_on == 'true':
        for off_jacket_fabric in dummy_off_jacket_fabric_list:
            if not off_jacket_fabric.product.product_type.name == 'jacket':
                off_jacket_fabric_list.append(off_jacket_fabric)
        for fabric in dummy_fabric_list:
            if not fabric.product.product_type.name == 'vest':
                fabric_list.append(fabric)
    else:
        fabric_list = dummy_fabric_list
        for off_jacket_fabric in dummy_off_jacket_fabric_list:
            if off_jacket_fabric.product.product_type.name == 'jacket':
                only_jacket = True
            else:
                off_jacket_fabric_list.append(off_jacket_fabric)

    mannequin = Mannequin.objects.get(id=mannequin_id)
    model_front_image = Image.open(mannequin.front)
    model_back_image = Image.open(mannequin.back)

    # 앞모습 합성
    mapping_image_file_name = mannequin.gender + '_front_image' + get_random_string(length=12) + '.png'
    mapping_image = image_composite(model_front_image, fabric_list, 'front')
    fitting.front_image.save(mapping_image_file_name, ContentFile(mapping_image.read()))
    mapping_image.close()

    # 뒷모습 합성
    # model_image = Image.open(mannequin.back)
    mapping_image_file_name = mannequin.gender + '_back_image' + get_random_string(length=12) + '.png'
    mapping_image = image_composite(model_back_image, fabric_list, 'back')
    fitting.back_image.save(mapping_image_file_name, ContentFile(mapping_image.read()))
    mapping_image.close()

    if jacket_vest_on == 'true' or only_jacket:
        mannequin = Mannequin.objects.get(id=mannequin_id)
        model_front_image = Image.open(mannequin.front)
        model_back_image = Image.open(mannequin.back)

        # 자켓없는 버전 앞모습 합성
        # model_image = Image.open(mannequin.front)
        mapping_image_file_name = mannequin.gender + '_off_jacket_front_image' + get_random_string(length=12) + '.png'
        mapping_image = image_composite(model_front_image, off_jacket_fabric_list, 'front')
        fitting.jacket_off_front_image.save(mapping_image_file_name, ContentFile(mapping_image.read()))
        mapping_image.close()

        # 자켓없는 버전 뒷모습 합성
        # model_image = Image.open(mannequin.back)
        mapping_image_file_name = mannequin.gender + '_off_jacket_back_image' + get_random_string(length=12) + '.png'
        mapping_image = image_composite(model_back_image, off_jacket_fabric_list, 'back')
        fitting.jacket_off_back_image.save(mapping_image_file_name, ContentFile(mapping_image.read()))
        mapping_image.close()
    pass


# 실제 합성 처리 합성한 이미지 리턴
def image_composite(model_image, fabric_list, front_back):
    for fabric in fabric_list:

        if not(fabric.product.product_type.name == 'acc' and front_back == 'back'):
            if front_back == 'front':
                fabric_mapping_image = fabric.front_mapping_image
            else:
                fabric_mapping_image = fabric.back_mapping_image

            # fabric_mapping_image.seek(0)
            with Image.open(fabric_mapping_image) as composite_material:
                with model_image as composite_image:
                    model_image = Image.alpha_composite(composite_image, composite_material)
                    # composite_material.seek(0)

            # temp_handle = StringIO()
            # fabric_mapping_image.save(temp_handle, 'PNG')
            # temp_handle.seek(0)
            # material_image = ContentFile(temp_handle.read())
            # temp_handle.close()
            # with Image.open(material_image) as composite_material:
            #     with model_image as composite_image:
            #         model_image = Image.alpha_composite(composite_image, composite_material)

    model_image.thumbnail((200, 494), Image.ANTIALIAS)

    temp_handle = StringIO()
    model_image.save(temp_handle, 'PNG')
    temp_handle.seek(0)
    mapping_image = ContentFile(temp_handle.read())
    temp_handle.close()

    return mapping_image
