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

from django.views.generic import TemplateView
from django.shortcuts import render_to_response
from django.http.response import HttpResponse
from django.template import RequestContext

from mysite.settings import MEDIA_ROOT
from simulation.models import Product, Mannequin, Couple, ElectronicBookCatalog
from simulation.custom_admin.functions import get_product_context_data, z_index_sort
from simulation.custom_admin.create_couple import create_new_couple_as_type, \
    origin_couple_fittings_relation_clear_and_image_composite


class HomeView(TemplateView):
    template_name = 'simulation/custom_admin/mapping/mapping.html'

    def get_context_data(self, **kwargs):
        context = super(HomeView, self).get_context_data(**kwargs)
        self.request.session['sim_type'] = 'admin'
        context['selectedCategory'] = 'design'
        context['selectedSubCategory'] = 'couple'
        return context


# 함수형 리로드 뷰  지금은 안쓴다
# def center_list_change(request):
#     context = {}
#     template_name = 'simulation/custom_admin/mapping/center_list.html'
#     context['season'] = request.GET.get('season')
#     context['style'] = request.GET.get('style')
#     context['coupleCategory'] = request.GET.get('coupleCategory')
#     context['isSlide'] = request.GET.get('isSlide')
#     return render_to_response(template_name, context)


# 슬라이드 리스트 출력 뷰
class CenterListChangeView(TemplateView):
    template_name = 'simulation/custom_admin/mapping/center_list.html'

    def get(self, request, *args, **kwargs):
        context = super(CenterListChangeView, self).get_context_data(**kwargs)
        season = self.request.GET.get('season')
        style = self.request.GET.get('style')
        couple_type= self.request.GET.get('couple_category')

        final_fitting_id = self.request.GET.get('final_fitting_id')
        favorite_check_couple_list = []

        couple_list = Couple.objects.filter(
            boy_fitting__fitting_category__season=season,
            boy_fitting__fitting_category__style=style,
            boy_fitting__fitting_category__gender='boy',
            girl_fitting__fitting_category__season=season,
            girl_fitting__fitting_category__style=style,
            girl_fitting__fitting_category__gender='girl',
            type=couple_type
        ).order_by('name')

        if couple_type == 'normal':
            couple_list = couple_list.filter(user=request.user)

        for couple in couple_list:
            # for favorite_couple_set in couple.selectedfavoritecoupleset_set.filter(fi)
            if couple.selectedfavoritecoupleset_set.filter(final_uniform_set_id=final_fitting_id).__len__() > 0:
                couple.favorite_check = True
            favorite_check_couple_list.append(couple)

        context['couple_list'] = favorite_check_couple_list
        context['couple_type'] = couple_type
        self.request.session['couple_type'] = couple_type
        context['sim_type'] = self.request.session['sim_type']

        return render_to_response(self.get_template_names(), context, context_instance=RequestContext(self.request))


# 슬라이드 왼쪽 리스트 출력 뷰
class LeftListChangeView(TemplateView):
    template_name = 'simulation/custom_admin/mapping/left_menu_container_couple_list.html'

    def get(self, request, *args, **kwargs):
        context = super(LeftListChangeView, self).get_context_data(**kwargs)
        couple_list = Couple.objects.filter(
            boy_fitting__fitting_category__season=self.request.GET.get('season'),
            boy_fitting__fitting_category__style=self.request.GET.get('style'),
            boy_fitting__fitting_category__gender='boy',
            girl_fitting__fitting_category__season=self.request.GET.get('season'),
            girl_fitting__fitting_category__style=self.request.GET.get('style'),
            girl_fitting__fitting_category__gender='girl',
            type=self.request.GET.get('couple_category')
        ).order_by('name')

        if self.request.GET.get('couple_category') == 'normal':
            couple_list = couple_list.filter(user=request.user)

        context['couple_list'] = couple_list
        return render_to_response(self.get_template_names(), context)


# 프로덕트 리스트 출력 뷰 (첫진입때만 발생 카테고리와 오브젝트 다 갖고옴)
class GetProductListView(TemplateView):
    template_name = 'simulation/custom_admin/mapping/coordi/product_tab.html'

    def get(self, request, *args, **kwargs):
        context = super(GetProductListView, self).get_context_data(**kwargs)
        season = self.request.GET.get('season')
        style = self.request.GET.get('style')

        context = get_product_context_data(context, season, style)

        return render_to_response(self.get_template_names(), context)


# 페브릭 카테고리 리스트 출력 뷰 (첫진입때만 발생)
class GetFabricCategoryListView(TemplateView):
    template_name = 'simulation/custom_admin/mapping/coordi/fabric_tab.html'

    def get(self, request, *args, **kwargs):
        context = super(GetFabricCategoryListView, self).get_context_data(**kwargs)
        season = self.request.GET.get('season')
        style = self.request.GET.get('style')

        context = get_product_context_data(context, season, style)

        return render_to_response(self.get_template_names(), context)


# 프로덕트 클릭 후 페브릭 오브젝트들 출력 기능 뷰
class GetFabricContentListView(TemplateView):
    template_name = 'simulation/custom_admin/mapping/coordi/fabric_tab_detail.html'

    def get(self, request, *args, **kwargs):
        context = super(GetFabricContentListView, self).get_context_data(**kwargs)
        product_id = self.request.GET.get('product_id')

        main_fabric_list = Product.objects.get(id=product_id).mainfabric_set.all().order_by('id')

        for main_fabric in main_fabric_list:
            main_fabric.name = main_fabric.name.split('.')[0]

        context['main_fabric_list'] = main_fabric_list

        return render_to_response(self.get_template_names(), context)


# 메인 코디 출력기능  선택된 페브릭 오브젝트들 가져온다
class GetCoordiCenterView(TemplateView):
    template_name = 'simulation/custom_admin/mapping/coordi/coordi_center.html'

    def get(self, request, *args, **kwargs):
        context = super(GetCoordiCenterView, self).get_context_data(**kwargs)

        season = self.request.GET.get('season')
        style = self.request.GET.get('style')
        gender = self.request.GET.get('gender')

        context['mannequin'] = Mannequin.objects.get(season=season, style=style, gender=gender)

        # 자바스크립트에서 리스트를 보낼때는 getlist로 받아야한다 변수명 + [] 는 필수
        coordi_fabric_list = self.request.GET.getlist('coordi_fabric_list[]')
        context['fabric_list'] = z_index_sort(coordi_fabric_list)

        return render_to_response(self.get_template_names(), context)


# 새로운 커플 생성하기 뷰
def new_couple_save(request):
    couple_save_type = request.GET.get('couple_save_type')

    if couple_save_type == 'new_couple_popular':
        create_new_couple_as_type(request, 'popular')
    elif couple_save_type == 'new_couple_catalog':
        create_new_couple_as_type(request, 'catalog')
    elif couple_save_type == 'new_couple_normal':
        create_new_couple_as_type(request, 'normal')
    else:
        raise
    result_data = {'success': True}
    return HttpResponse(json.dumps(result_data, indent=4, ensure_ascii=False, encoding='utf-8'))


# 기존 커플 수정하기 뷰
def origin_couple_update(request):

    # create_couple.py에 있다
    origin_couple_fittings_relation_clear_and_image_composite(request)

    result_data = {'success': True}
    return HttpResponse(json.dumps(result_data, indent=4, ensure_ascii=False, encoding='utf-8'))


# 자켓 뒷모습 판별후 남자 여자 url 변경 함수
def change_slide_back_jacket(request):
    couple_id = request.GET.get('couple_id')
    is_back = request.GET.get('is_back')
    is_jacket_off = request.GET.get('is_jacket_off')

    couple = Couple.objects.get(id=couple_id)
    boy_fitting_url = ''
    girl_fitting_url = ''

    if is_back == 'true':
        if is_jacket_off == 'true':
            if couple.boy_fitting.jacket_off_back_image:
                boy_fitting_url = couple.boy_fitting.jacket_off_back_image.url
            else:
                boy_fitting_url = couple.boy_fitting.back_image.url
            if couple.girl_fitting.jacket_off_back_image:
                girl_fitting_url = couple.girl_fitting.jacket_off_back_image.url
            else:
                girl_fitting_url = couple.girl_fitting.back_image.url
        else:
            boy_fitting_url = couple.boy_fitting.back_image.url
            girl_fitting_url = couple.girl_fitting.back_image.url
    else:
        if is_jacket_off == 'true':
            # boy_fitting_url = couple.boy_fitting.jacket_off_front_image.url
            # girl_fitting_url = couple.girl_fitting.jacket_off_front_image.url
            if couple.boy_fitting.jacket_off_front_image:
                boy_fitting_url = couple.boy_fitting.jacket_off_front_image.url
            else:
                boy_fitting_url = couple.boy_fitting.front_image.url
            if couple.girl_fitting.jacket_off_front_image:
                girl_fitting_url = couple.girl_fitting.jacket_off_front_image.url
            else:
                girl_fitting_url = couple.girl_fitting.front_image.url
        else:
            boy_fitting_url = couple.boy_fitting.front_image.url
            girl_fitting_url = couple.girl_fitting.front_image.url

    result_data = {'boyFittingUrl': boy_fitting_url, 'girlFittingUrl': girl_fitting_url}
    return HttpResponse(json.dumps(result_data, indent=4, ensure_ascii=False, encoding='utf-8'))


# 선택된 커플의 코디로 들어가기~~
def get_couples_main_fabric(request):
    boy_context_list = []
    girl_context_list = []
    couple_id = request.GET.get('couple_id')
    couple = Couple.objects.get(id=couple_id)

    for boy_fabric in couple.boy_fitting.product_set.all():
        boy_fabric_context = {
            'fabric_index': boy_fabric.id,
            'product_index': boy_fabric.product.id,
            'product_category': 'boy' + boy_fabric.product.product_type.name.title().replace('-', '') + 'Category'
        }
        boy_context_list.append(boy_fabric_context)

    for girl_fabric in couple.girl_fitting.product_set.all():
        girl_fabric_context = {
            'fabric_index': girl_fabric.id,
            'product_index': girl_fabric.product.id,
            'product_category': 'girl' + girl_fabric.product.product_type.name.title().replace('-', '') + 'Category'
        }
        girl_context_list.append(girl_fabric_context)

    result_data = {
        'boy_context_list': boy_context_list,
        'girl_context_list': girl_context_list,
        'couple_name': couple.name,
    }
    return HttpResponse(json.dumps(result_data, indent=4, ensure_ascii=False, encoding='utf-8'))


# 슬라이드에서 커플 삭제하기 기능
def couple_delete(request):
    couple_id = request.GET.get('couple_id')
    couple = Couple.objects.get(id=couple_id)

    shutil.rmtree(MEDIA_ROOT + '/fitting/' + str(couple.boy_fitting.id))
    shutil.rmtree(MEDIA_ROOT + '/fitting/' + str(couple.girl_fitting.id))

    couple.delete()

    result_data = {'msg': 'success'}
    return HttpResponse(json.dumps(result_data, indent=4, ensure_ascii=False, encoding='utf-8'))


# 커플 상세보기 기능
class CoupleDetailView(TemplateView):
    template_name = 'simulation/custom_admin/mapping/model_information.html'

    def get(self, request, *args, **kwargs):
        context = super(CoupleDetailView, self).get_context_data(**kwargs)

        couple = Couple.objects.get(id=self.request.GET.get('couple_id'))
        boy_main_fabric_list = couple.boy_fitting.product_set.all().order_by("product__product_type_id")
        girl_main_fabric_list = couple.girl_fitting.product_set.all().order_by("product__product_type_id")

        context['couple'] = couple
        context['boy_main_fabric_list'] = boy_main_fabric_list
        context['girl_main_fabric_list'] = girl_main_fabric_list

        return render_to_response(self.get_template_names(), context, context_instance=RequestContext(self.request))


def get_catalog_image(request):

    couple_id = request.GET.get('couple_id')

    try:
        catalog_image_url = Couple.objects.get(id=couple_id).electronicbookcatalog.catalog_image.url
    except:
        catalog_image_url = '/static/base/image/no-image-available.jpg'

    result_data = {'catalog_image_url': catalog_image_url}
    return HttpResponse(json.dumps(result_data, indent=4, ensure_ascii=False, encoding='utf-8'))


def catalog_image_registration(request):

    couple_id = request.POST.get('couple_id')
    catalog_image_file = request.FILES['catalog-image']

    couple = Couple.objects.get(id=couple_id)
    try:
        e_book_catalog = couple.electronicbookcatalog
        e_book_catalog.catalog_image = catalog_image_file
        e_book_catalog.save()
    except:
        e_book_catalog = ElectronicBookCatalog.objects.create(couple=couple)
        e_book_catalog.catalog_image = catalog_image_file
        e_book_catalog.save()

    result_data = {'catalog_image_url': e_book_catalog.catalog_image.url}
    return HttpResponse(json.dumps(result_data, indent=4, ensure_ascii=False, encoding='utf-8'))


def catalog_image_delete(request):

    couple_id = request.GET.get('couple_id')
    e_book_catalog = Couple.objects.get(id=couple_id).electronicbookcatalog
    e_book_catalog.delete()

    catalog_image_url = '/static/base/image/no-image-available.jpg'
    result_data = {'catalog_image_url': catalog_image_url}
    return HttpResponse(json.dumps(result_data, indent=4, ensure_ascii=False, encoding='utf-8'))