# -*- coding: utf-8 -*-
from django.contrib.auth.decorators import login_required
from django.contrib.admin.views.decorators import staff_member_required
# from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseRedirect
from django.utils.decorators import classonlymethod
from django.views.generic.base import View

from kindergarten.models import Kindergarten
from order_contract.models import OrderContract

# Create your views here.
# 로그인 판별 클래스
# 원하는 뷰에 인자로 첫번째에 넣으면 된다. 로그인페이지의 url은 setting.py에 LOGIN_URL로 알수있다
# 여기서는 지정하지 않았으므로 디폴트값 '/accounts/login/'로 찾아간다.
class LoginRequiredMixin(object):
    @classmethod
    def as_view(cls, **initkwargs):
        view = super(LoginRequiredMixin, cls).as_view(**initkwargs)
        return login_required(view)


# 비슷한 기능의 관리자 판별 클래스
# user의 is_staff 가 true 인 경우만 접근할수 있음
class AdminRequiredMixin(object):
    @classmethod
    def as_view(cls, **initkwargs):
        view = super(AdminRequiredMixin, cls).as_view(**initkwargs)
        return staff_member_required(view)


# 페이징 계산 기능 PaginationMixin 생성뒤로는 더이상쓰지 않는다
def page_calc(paginator, page):
    page_numbers_range = 5  # Display only 5 page numbers
    max_index = len(paginator.page_range)
    current_page = int(page) if page else 1

    start_index = int((current_page - 1) / page_numbers_range) * page_numbers_range
    end_index = start_index + page_numbers_range
    if end_index >= max_index:
        end_index = max_index

    page_range = list(i for i in paginator.page_range)

    return page_range[start_index:end_index]


# 페이징 기능 믹스인
class PaginationMixin(object):
    def get_context_data(self, **kwargs):
        context = super(PaginationMixin, self).get_context_data(**kwargs)
        paginator = context['paginator']
        page_numbers_range = 5  # Display only 5 page numbers
        max_index = len(paginator.page_range)

        page = self.request.GET.get('page')
        current_page = int(page) if page else 1

        start_index = int((current_page - 1) / page_numbers_range) * page_numbers_range
        end_index = start_index + page_numbers_range
        if end_index >= max_index:
            end_index = max_index

        page_range = list(i for i in  paginator.page_range)
        context['page_range'] = page_range[start_index:end_index]
        context['first_page'] = 1
        context['last_page'] = paginator.num_pages
        return context


class OwnerRequiredMixin(object):
    @classonlymethod
    def as_view(cls, **initkwargs):
        view = super(OwnerRequiredMixin, cls).as_view(**initkwargs)
        return owner_required_decorator(view)


def owner_required_decorator(view):
    def wrap(request, *args, **kwargs):
        try:
            kindergarten_id = kwargs['kindergarten_id']
        except:
            kindergarten_id = 0

        if kindergarten_id > 0:
            kindergarten = Kindergarten.objects.get(id=kindergarten_id)
            if kindergarten.user_profile.user == request.user or request.user.username == 'admin':
                return view(request, *args, **kwargs)
            else:
                return HttpResponseRedirect('/')

        try:
            order_id = kwargs['order_id']
        except:
            order_id = 0

        if order_id > 0:
            order = OrderContract.objects.get(id=order_id)
            if order.kindergarten.user_profile.user == request.user or request.user.username == 'admin':
                return view(request, *args, **kwargs)
            else:
                return HttpResponseRedirect('/')
    return wrap

class OrderStatusMixin(object):
    @classonlymethod
    def as_view(cls, **initkwargs):
        view = super(OrderStatusMixin, cls).as_view(**initkwargs)
        return order_status_decorator(view)

def order_status_decorator(view):
    def wrap(request, *args, **kwargs):
        try:
            order_id = kwargs['order_id']
        except:
            order_id = 0

        if order_id > 0:
            order = OrderContract.objects.get(id=order_id)
            if order.order_status < 5 :
                return view(request, *args, **kwargs)
            else:
                return HttpResponseRedirect('/')

    return wrap