# -*- coding: utf-8 -*-
import shutil

from django.core.files.base import ContentFile
from django.utils.crypto import get_random_string

from PIL import Image
from cStringIO import StringIO

from mysite.settings import MEDIA_ROOT
from simulation.custom_admin.image_composite import image_composite_controller
from simulation.models import FittingCategory, Fitting, Mannequin, Couple
from simulation.custom_admin.functions import z_index_sort


# 커플이미지 남녀 합성
def boy_and_girl_image_composite(boy_field_image, girl_field_image):

    boy_pil_image = Image.open(boy_field_image)
    girl_pil_image = Image.open(girl_field_image)

    width = 351
    height = boy_field_image.height

    couple_temp_image = Image.new('RGBA', (width, height))
    couple_temp_image.paste(boy_pil_image, (0, 0), boy_pil_image)
    couple_temp_image.paste(girl_pil_image, (155, 0), girl_pil_image)

    temp_handle = StringIO()
    couple_temp_image.save(temp_handle, 'PNG')
    temp_handle.seek(0)
    couple_image = ContentFile(temp_handle.read())
    temp_handle.close()

    # 여기서 꼭 닫아줘야 한다
    # 안그러면 기존커플로저장하고 모달창 안끄고 변경해서 저장할때 파일이 열려있어서 파일 삭제를 못한다
    boy_field_image.close()
    girl_field_image.close()

    return couple_image


# 새로운 커플 타입별로 생성하기
def create_new_couple_as_type(request, couple_type):
    season = request.GET.get('season')
    style = request.GET.get('style')
    boy_jacket_vest_on = request.GET.get('boy_jacket_vest_on')
    girl_jacket_vest_on = request.GET.get('girl_jacket_vest_on')
    boy_fabric_index_list = request.GET.getlist('boy_fabric_index_list[]')
    girl_fabric_index_list = request.GET.getlist('girl_fabric_index_list[]')
    # current_couple_id = request.GET.get('current_couple_id')
    new_couple_name = request.GET.get('new_couple_name')

    boy_fitting_category = FittingCategory.objects.get(season__icontains=season, style__icontains=style, gender__icontains='boy')
    boy_fitting = Fitting.objects.create(fitting_category=boy_fitting_category)
    boy_mannequin_id = Mannequin.objects.get(season=season, style=style, gender='boy').id

    image_composite_parameters = {
        'fitting': boy_fitting,
        'mannequin_id': boy_mannequin_id,
        'fabric_index_list': boy_fabric_index_list,
        'jacket_vest_on': boy_jacket_vest_on
    }

    image_composite_controller(image_composite_parameters)

    boy_fabric_list = z_index_sort(boy_fabric_index_list)
    for boy_fabric in boy_fabric_list:
        boy_fitting.product_set.add(boy_fabric)

    girl_fitting_category = FittingCategory.objects.get(season__icontains=season, style__icontains=style, gender__icontains='girl')
    girl_fitting = Fitting.objects.create(fitting_category=girl_fitting_category)
    girl_mannequin_id = Mannequin.objects.get(season=season, style=style, gender='girl').id

    image_composite_parameters = {
        'fitting': girl_fitting,
        'mannequin_id': girl_mannequin_id,
        'fabric_index_list': girl_fabric_index_list,
        'jacket_vest_on': girl_jacket_vest_on
    }

    image_composite_controller(image_composite_parameters)

    girl_fabric_list = z_index_sort(girl_fabric_index_list)
    for girl_fabric in girl_fabric_list:
        girl_fitting.product_set.add(girl_fabric)

    # 남녀 앞모습 합성
    couple_front_image = boy_and_girl_image_composite(boy_fitting.front_image, girl_fitting.front_image)

    # 남녀 뒷모습 합성
    couple_back_image = boy_and_girl_image_composite(boy_fitting.back_image, girl_fitting.back_image)

    # 커플 생성 후 이미지들 저장
    couple = Couple.objects.create(boy_fitting=boy_fitting,
                                   girl_fitting=girl_fitting,
                                   type=couple_type,
                                   user=request.user,
                                   name=new_couple_name
                                   )

    couple.front_image.save('couple_front_image' + get_random_string(length=12) + '.png', ContentFile(couple_front_image.read()))
    couple.back_image.save('couple_back_image' + get_random_string(length=12) + '.png', ContentFile(couple_back_image.read()))

    pass


# 기존커플의 남자여자 fitting의 product_set 관계만 지우고 새로 맺어준다 이미지 합성은 동일
def origin_couple_fittings_relation_clear_and_image_composite(request):
    season = request.GET.get('season')
    style = request.GET.get('style')
    boy_jacket_vest_on = request.GET.get('boy_jacket_vest_on')
    girl_jacket_vest_on = request.GET.get('girl_jacket_vest_on')
    boy_fabric_index_list = request.GET.getlist('boy_fabric_index_list[]')
    girl_fabric_index_list = request.GET.getlist('girl_fabric_index_list[]')
    current_couple_id = request.GET.get('current_couple_id')

    couple = Couple.objects.get(id=current_couple_id)
    shutil.rmtree(MEDIA_ROOT + '/couple/' + str(couple.id))
    shutil.rmtree(MEDIA_ROOT + '/fitting/' + str(couple.boy_fitting.id))
    shutil.rmtree(MEDIA_ROOT + '/fitting/' + str(couple.girl_fitting.id))

    boy_fitting = couple.boy_fitting
    boy_mannequin_id = Mannequin.objects.get(season=season, style=style, gender='boy').id

    image_composite_parameters = {
        'fitting': boy_fitting,
        'mannequin_id': boy_mannequin_id,
        'fabric_index_list': boy_fabric_index_list,
        'jacket_vest_on': boy_jacket_vest_on
    }

    image_composite_controller(image_composite_parameters)

    boy_fitting.product_set.clear()
    boy_fabric_list = z_index_sort(boy_fabric_index_list)
    for boy_fabric in boy_fabric_list:
        boy_fitting.product_set.add(boy_fabric)

    girl_fitting = couple.girl_fitting
    girl_mannequin_id = Mannequin.objects.get(season=season, style=style, gender='girl').id

    image_composite_parameters = {
        'fitting': girl_fitting,
        'mannequin_id': girl_mannequin_id,
        'fabric_index_list': girl_fabric_index_list,
        'jacket_vest_on': girl_jacket_vest_on
    }

    image_composite_controller(image_composite_parameters)

    girl_fitting.product_set.clear()
    girl_fabric_list = z_index_sort(girl_fabric_index_list)
    for girl_fabric in girl_fabric_list:
        girl_fitting.product_set.add(girl_fabric)

    # 남녀 앞모습 합성
    couple_front_image = boy_and_girl_image_composite(boy_fitting.front_image, girl_fitting.front_image)

    # 남녀 뒷모습 합성
    couple_back_image = boy_and_girl_image_composite(boy_fitting.back_image, girl_fitting.back_image)

    couple.name = request.GET.get('origin_couple_name')
    couple.front_image.save('couple_front_image' + get_random_string(length=12) + '.png', ContentFile(couple_front_image.read()))
    couple.back_image.save('couple_back_image' + get_random_string(length=12) + '.png', ContentFile(couple_back_image.read()))
    couple.save()

    pass
