# -*- coding: utf-8 -*-
from __future__ import absolute_import

import json

from django.http import HttpResponse
from django.views.generic import TemplateView, RedirectView
from django.core.urlresolvers import reverse_lazy

from order_contract.models import OrderContract
from company.models import Company
from measurement.models import Kindergartener, DisplaySizeImage, Size
from measurement.size_recommend.function import get_checked_size
from measurement.authentication_code import AuthenticationCheckMixin


class IntroTemplateView(AuthenticationCheckMixin, TemplateView):
    template_name = 'measurement/size_recommend/intro.html'

    def get_context_data(self, **kwargs):
        context = super(IntroTemplateView, self).get_context_data(**kwargs)
        order = OrderContract.objects.get(id=self.kwargs['order_id'])
        context['order_id'] = order.id
        context['kindergarten_name'] = order.kindergarten.name
        return context


def kindergartener_name_check(request):

    order = OrderContract.objects.get(id=request.GET.get('order_id'))
    name = request.GET.get('name')

    kindergartener = order.kindergartener_set.filter(name=name)

    if kindergartener.__len__() > 0:
        result_data = {
            'msg': '동일한 이름이 있습니다. 기존 데이터로 이동합니다.',
            'kindergartenerIndex': kindergartener[0].id
        }
        return HttpResponse(json.dumps(result_data, indent=4, ensure_ascii=False, encoding='utf-8'))
    else:
        raise


class IntroUpdateTemplateView(TemplateView):
    template_name = 'measurement/size_recommend/intro_update.html'

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

        kindergartener = Kindergartener.objects.get(id=self.kwargs['kindergartener_id'])
        context['kindergartener'] = kindergartener
        context['kindergarten_name'] = kindergartener.order_contract.kindergarten.name

        return context


class KindergartenerCV(RedirectView):
    def get_redirect_url(self, *args, **kwargs):
        order = OrderContract.objects.get(id=self.kwargs['order_id'])
        kindergartener = Kindergartener()
        kindergartener.order_contract = order
        kindergartener.name = self.request.POST.get('name')
        kindergartener.group = self.request.POST.get('class')
        kindergartener.birth_date = self.request.POST.get('birth')
        kindergartener.gender = self.request.POST.get('gender')
        kindergartener.save()
        return reverse_lazy('measurement:size_recommend:body_information_input',
                            kwargs={'kindergartener_id': kindergartener.id})


class KindergartenerUV(RedirectView):
    def get_redirect_url(self, *args, **kwargs):
        kindergartener = Kindergartener.objects.get(id=self.kwargs['kindergartener_id'])
        kindergartener.name = self.request.POST.get('name')
        kindergartener.group = self.request.POST.get('class')
        kindergartener.birth_date = self.request.POST.get('birth')
        kindergartener.gender = self.request.POST.get('gender')
        kindergartener.save()
        return reverse_lazy('measurement:size_recommend:body_information_input',
                            kwargs={'kindergartener_id': kindergartener.id})


class BodyInformationInputView(AuthenticationCheckMixin, TemplateView):
    template_name = 'measurement/size_recommend/body_information_input.html'

    def get_context_data(self, **kwargs):
        context = super(BodyInformationInputView, self).get_context_data(**kwargs)
        kindergartener = Kindergartener.objects.get(id=self.kwargs['kindergartener_id'])
        context['kindergartener'] = kindergartener
        return context


class BodyInformationSaveView(RedirectView):
    def get_redirect_url(self, *args, **kwargs):
        kindergartener = Kindergartener.objects.get(id=self.kwargs['kindergartener_id'])
        kindergartener.height = self.request.POST.get('height')
        kindergartener.weight = self.request.POST.get('weight')
        kindergartener.waist = self.request.POST.get('waist')
        kindergartener.shoulder = self.request.POST.get('shoulder')
        kindergartener.save()
        # return reverse_lazy('measurement:size_recommend:get_size_recommend',
        #                     kwargs={'kindergartener_id': kindergartener.id})
        return reverse_lazy('measurement:size_recommend:selected_couple_list',
                            kwargs={'kindergartener_id': kindergartener.id})


class SelectedCoupleListView(TemplateView):
    template_name = 'measurement/size_recommend/selected_couple_list.html'

    def get_context_data(self, **kwargs):
        context = super(SelectedCoupleListView, self).get_context_data(**kwargs)
        kindergartener = Kindergartener.objects.get(id=self.kwargs['kindergartener_id'])

        context['kindergartener_id'] = kindergartener.id

        context['winter_formal'] = kindergartener.order_contract.get_selected_couple('winter', 'formal')
        context['winter_training'] = kindergartener.order_contract.get_selected_couple('winter', 'training')
        context['summer_formal'] = kindergartener.order_contract.get_selected_couple('summer', 'formal')
        context['summer_training'] = kindergartener.order_contract.get_selected_couple('summer', 'training')

        return context


class GetSizeRecommendView(TemplateView):
    template_name = 'measurement/size_recommend/get_size_recommend.html'

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

        kindergartener = Kindergartener.objects.get(id=self.kwargs['kindergartener_id'])

        context['winter_formal'] = kindergartener.order_contract.get_selected_couple('winter', 'formal')
        context['winter_training'] = kindergartener.order_contract.get_selected_couple('winter', 'training')
        context['summer_formal'] = kindergartener.order_contract.get_selected_couple('summer', 'formal')
        context['summer_training'] = kindergartener.order_contract.get_selected_couple('summer', 'training')

        if context['winter_formal']:
            season = 'winter'
            style = 'formal'
        elif context['winter_training']:
            season = 'winter'
            style = 'training'
        elif context['summer_formal']:
            season = 'summer'
            style = 'formal'
        else:
            season = 'summer'
            style = 'training'

        try:
            season = self.kwargs['season']
        except:
            season = season
        try:
            style = self.kwargs['style']
        except:
            style = style

        context['kindergartener_id'] = kindergartener.id
        context['season'] = season
        context['style'] = style
        context[season+style] = 'selected'

        context['selected_couple'] = kindergartener.order_contract.get_selected_couple(season=season, style=style)

        checked_size = get_checked_size(kindergartener.height)

        try:
            size = Size.objects.get(kindergartener=kindergartener, season__iexact=season, style__iexact=style)
            upgrade_size_integer = size.checked_size - checked_size
            upgrade_size_integer = 20 if upgrade_size_integer > 20 else upgrade_size_integer
        except:
            print '고른사이즈 없음'
            upgrade_size_integer = None

        display_size_image_list = DisplaySizeImage.objects.filter(
            season__iexact=season,
            style__iexact=style,
            gender__iexact=kindergartener.gender
        ).order_by("size_upgrade")

        recommend_list = []
        if type(upgrade_size_integer) == int:
            for display_size_image in display_size_image_list:
                if display_size_image.size_upgrade == upgrade_size_integer:
                    display_size_image.selected = 'selected'
                else:
                    display_size_image.selected = ''
                display_size_image.current_size = checked_size + display_size_image.size_upgrade
                recommend_list.append(display_size_image)
        else:
            for display_size_image in display_size_image_list:
                display_size_image.current_size = checked_size + display_size_image.size_upgrade
                recommend_list.append(display_size_image)
            # recommend_list = display_size_image_list

        # context['normal_size'] = recommend_list[0]
        # if checked_size < 129:
        #     context['one_up_size'] = recommend_list[1]
        # if checked_size < 119:
        #     context['two_up_size'] = recommend_list[2]
        context['normal_size'] = recommend_list[0]
        context['one_up_size'] = recommend_list[1]
        context['two_up_size'] = recommend_list[2]

        return context


def display_image_reload(request):
    normal_id = request.GET.get('normal_id')
    one_up_id = request.GET.get('one_up_id')
    two_up_id = request.GET.get('two_up_id')

    jacket_on_off = request.GET.get('jacket_on_off')
    front_on_off = request.GET.get('front_on_off')

    if jacket_on_off == 'on' and front_on_off=='on':
        normal_size_image_url = DisplaySizeImage.objects.get(id=normal_id).front_image.url
        one_up_size_image_url = DisplaySizeImage.objects.get(id=one_up_id).front_image.url
        two_up_size_image_url = DisplaySizeImage.objects.get(id=two_up_id).front_image.url
    elif jacket_on_off == 'on' and front_on_off=='off':
        normal_size_image_url = DisplaySizeImage.objects.get(id=normal_id).back_image.url
        one_up_size_image_url = DisplaySizeImage.objects.get(id=one_up_id).back_image.url
        two_up_size_image_url = DisplaySizeImage.objects.get(id=two_up_id).back_image.url
    elif jacket_on_off == 'off' and front_on_off=='on':
        normal_size_image_url = DisplaySizeImage.objects.get(id=normal_id).jacket_off_front_image.url
        one_up_size_image_url = DisplaySizeImage.objects.get(id=one_up_id).jacket_off_front_image.url
        two_up_size_image_url = DisplaySizeImage.objects.get(id=two_up_id).jacket_off_front_image.url
    else:
        normal_size_image_url = DisplaySizeImage.objects.get(id=normal_id).jacket_off_back_image.url
        one_up_size_image_url = DisplaySizeImage.objects.get(id=one_up_id).jacket_off_back_image.url
        two_up_size_image_url = DisplaySizeImage.objects.get(id=two_up_id).jacket_off_back_image.url

    result_data = {
        'normalSizeImageUrl': normal_size_image_url,
        'oneUpSizeImageUrl': one_up_size_image_url,
        'twoUpSizeImageUrl': two_up_size_image_url,
    }
    return HttpResponse(json.dumps(result_data, indent=4, ensure_ascii=False, encoding='utf-8'))


def select_size(request):
    kindergartener = Kindergartener.objects.get(id=request.GET.get('kindergartener_id'))
    season = request.GET.get('season')
    style = request.GET.get('style')
    display_size_image= DisplaySizeImage.objects.get(id=request.GET.get('display_size_image_index'))

    height = kindergartener.height
    checked_size = get_checked_size(height) + display_size_image.size_upgrade

    # if checked_size > 130:
    #     checked_size = 130

    try:
        size = Size.objects.get(kindergartener=kindergartener, season__iexact=season, style__iexact=style)
        size.checked_size = checked_size
        size.save()
    except:
        Size.objects.create(kindergartener=kindergartener, season=season, style=style, checked_size=checked_size)

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


def selected_all_check(request):
    kindergartener = Kindergartener.objects.get(id=request.GET.get('kindergartener_id'))

    winter_formal = kindergartener.order_contract.get_selected_couple('winter', 'formal')
    winter_training = kindergartener.order_contract.get_selected_couple('winter', 'training')
    summer_formal = kindergartener.order_contract.get_selected_couple('summer', 'formal')
    summer_training = kindergartener.order_contract.get_selected_couple('summer', 'training')

    if winter_formal:
        winter_formal_size = kindergartener.size_set.filter(season__iexact='winter', style__iexact='formal')[0]
    if winter_training:
        winter_training_size = kindergartener.size_set.filter(season__iexact='winter', style__iexact='training')[0]
    if summer_formal:
        summer_formal_size = kindergartener.size_set.filter(season__iexact='summer', style__iexact='formal')[0]
    if summer_training:
        summer_training_size = kindergartener.size_set.filter(season__iexact='summer', style__iexact='training')[0]

    result_data = {
        'msg': '사이즈 선택이 완료되었습니다.',
    }
    return HttpResponse(json.dumps(result_data, indent=4, ensure_ascii=False, encoding='utf-8'))


class CompleteTemplateView(TemplateView):
    template_name = 'measurement/size_recommend/complete.html'

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

        kindergartener = Kindergartener.objects.get(id=self.kwargs['kindergartener_id'])
        company_url = kindergartener.order_contract.kindergarten.user_profile.company.hp_address

        if company_url:
            if company_url.find('http') < 0:
                context['company_url'] = 'http://' + company_url
            else:
                context['company_url'] = company_url

            if company_url.__len__() == 0:
                context['company_url'] = False

        return context
