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

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

from simulation.models import Couple, FinalFittingSet
from order_contract.models import OrderContract
from simulation.extend_admin_mapping.functions import get_selected_couple_set, get_selected_first_couple_exception, \
    get_favorite_couple_set
from core.views import LoginRequiredMixin, OwnerRequiredMixin, OrderStatusMixin


# 사용자 시뮬레이션 모드 첫진입 order를 가져와서 final fitting set 이 있으면 그걸넘기고 없으면 새로 만든다
# 세션에 시뮬레이션 타입을 normal을 준다 이 세션값으로 판별해서 관리자와 사용자모드에 각각 다른버튼이나 li등을 보여준다
class HomeView(OwnerRequiredMixin, OrderStatusMixin, LoginRequiredMixin, TemplateView):
    template_name = 'simulation/extend_admin_mapping/extend_admin_mapping.html'

    def get_context_data(self, **kwargs):
        context = super(HomeView, self).get_context_data(**kwargs)

        order_id = self.kwargs['order_id']
        order_contract = OrderContract.objects.get(id=order_id)

        simulation_status = 2
        if order_contract.order_status < simulation_status:
            order_contract.order_status = simulation_status
            order_contract.save()
        try:
            final_fitting_id = FinalFittingSet.objects.get(order_contract=order_contract).id
        except:
            final_fitting_id = FinalFittingSet.objects.create(order_contract=order_contract, name=order_contract.name).id

        try:
            couple_id = self.kwargs['couple_id']
            couple = Couple.objects.get(id=couple_id)
            context['couple_id'] = couple_id
            context['season'] = couple.boy_fitting.fitting_category.season
            context['style'] = couple.boy_fitting.fitting_category.style
            context['couple_type'] = couple.type
        except:
            context['couple_id'] = 0

        context['order_id'] = order_id
        context['final_fitting_id'] = final_fitting_id
        self.request.session['sim_type'] = 'normal'

        context['kindergarten'] = order_contract.kindergarten.name

        return context


# 현재 select된 커플들의 목록을 가져온다
# get_selected_couple_set로 목록을 가져온후 get_selected_first_couple_exception로 예외처리를 한다
# 목록이 하나도 없다면 (해당하는 select가 없으면) False를 줘서 리로드된 화면에 나오지 않는다
class SelectedCoupleListView(TemplateView):
    template_name = 'simulation/extend_admin_mapping/bottom/bottom_selected_list.html'

    def get(self, request, *args, **kwargs):
        context = super(SelectedCoupleListView, self).get_context_data(**kwargs)
        final_fitting = FinalFittingSet.objects.get(id=self.request.GET.get('final_fitting_id'))

        context['winter_formal'] = get_selected_first_couple_exception(final_fitting, 'winter', 'formal')
        context['winter_training'] = get_selected_first_couple_exception(final_fitting, 'winter', 'training')
        context['summer_formal'] = get_selected_first_couple_exception(final_fitting, 'summer', 'formal')
        context['summer_training'] = get_selected_first_couple_exception(final_fitting, 'summer', 'training')

        context['order_id'] = self.request.GET.get('order_id')

        return render_to_response(self.get_template_names(), context)


# 커플 세트하기
def couple_select(request):
    season = request.GET.get('season')
    style = request.GET.get('style')
    couple_id = request.GET.get('couple_id')
    final_fitting_id = request.GET.get('final_fitting_id')

    final_fitting = FinalFittingSet.objects.get(id=final_fitting_id)

    # 그전에 select된 관계를 검색해서 지우고 새로 맺어준다
    origin_selected_set_list = get_selected_couple_set(final_fitting, season, style)

    # 이미 있는거면 그냥 리턴해준다
    for selected_set in origin_selected_set_list:
        if selected_set.couple.id == int(couple_id):
            result_data = {'message': '이미 확정리스트에 있는 커플입니다.'}
            return HttpResponse(json.dumps(result_data, indent=4, ensure_ascii=False, encoding='utf-8'))

    for origin_selected_set in origin_selected_set_list:
        origin_selected_set.delete()

    final_fitting.selectedcoupleset_set.create(couple_id=couple_id)

    result_data = {'message': '등록되었습니다.'}
    return HttpResponse(json.dumps(result_data, indent=4, ensure_ascii=False, encoding='utf-8'))


# 커플 확정세트리스트에서 삭제하기
def selected_relation_cut(request):
    couple_id = request.GET.get('couple_id')
    final_fitting_id = request.GET.get('final_fitting_id')

    final_fitting = FinalFittingSet.objects.get(id=final_fitting_id)

    selected_set = final_fitting.selectedcoupleset_set.get(couple_id=couple_id)
    selected_set.delete()

    result_data = {'message': '삭제되었습니다.'}
    return HttpResponse(json.dumps(result_data, indent=4, ensure_ascii=False, encoding='utf-8'))


# 커플 관심리스트 리로드 뷰 season 및 style을 받아서 그에 맞는 리스트 반환
class FavoriteCoupleListView(TemplateView):
    template_name = 'simulation/extend_admin_mapping/bottom/bottom_favorite_list.html'

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

        season = self.request.GET.get('season')
        style = self.request.GET.get('style')
        final_fitting = FinalFittingSet.objects.get(id=self.request.GET.get('final_fitting_id'))

        favorite_couple_list = []
        favorite_couple_set_list = get_favorite_couple_set(final_fitting, season, style)

        for favorite_couple_set in favorite_couple_set_list:
            favorite_couple_list.append(favorite_couple_set.couple)

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


# 커플 관심리스트에 저장하기
def couple_favorite(request):
    season = request.GET.get('season')
    style = request.GET.get('style')
    couple_id = request.GET.get('couple_id')
    final_fitting_id = request.GET.get('final_fitting_id')

    final_fitting = FinalFittingSet.objects.get(id=final_fitting_id)

    favorite_couple_set_list = get_favorite_couple_set(final_fitting, season, style)

    if favorite_couple_set_list.__len__() > 2:
        result_data = {'message': '관심리스트는 최대 3개를 허용합니다.', 'error': 'star_image_off'}
        return HttpResponse(json.dumps(result_data, indent=4, ensure_ascii=False, encoding='utf-8'))

    for favorite_couple_set in favorite_couple_set_list:
        if favorite_couple_set.couple.id == int(couple_id):
            result_data = {'message': '이미 관심리스트에 있는 커플입니다.'}
            return HttpResponse(json.dumps(result_data, indent=4, ensure_ascii=False, encoding='utf-8'))

    final_fitting.selectedfavoritecoupleset_set.create(couple_id=couple_id)

    result_data = {'message': '관심리스트에 등록되었습니다.'}
    return HttpResponse(json.dumps(result_data, indent=4, ensure_ascii=False, encoding='utf-8'))


def favorite_relation_cut(request):
    couple_id = request.GET.get('couple_id')
    final_fitting_id = request.GET.get('final_fitting_id')

    final_fitting = FinalFittingSet.objects.get(id=final_fitting_id)

    favorite_set = final_fitting.selectedfavoritecoupleset_set.get(couple_id=couple_id)
    favorite_set.delete()

    result_data = {'message': '삭제되었습니다.'}
    return HttpResponse(json.dumps(result_data, indent=4, ensure_ascii=False, encoding='utf-8'))