# coding=utf-8

from rest_framework import permissions

from apps.customer.models import Customer
from apps.account.models import User
from apps.activity.models import Activity
from apps.WechatApplet.models import WechatApplet


class IsCustomerUser(permissions.BasePermission):
    def has_permission(self, request, view):
        if not request.user or not request.user.is_authenticated:
            return False
        if not request.user.type or request.user.type != User.CUSTOMER:
            return False

        appid = request.GET.get('appid', None)
        if not appid:
            appid = request.POST.get('appid')
        activity_id = request.GET.get('activity_id', None)
        if not activity_id:
            activity_id = request.POST.get('activity_id')

        try:
            WechatApplet.getByAppid(appid)
            activity = Activity.getById(activity_id)
        except:
            return False
        customer = Customer.objects.filter(branch_id=activity.branch_id, user_id=request.user.id).first()
        if not customer:
            return False
        request.customer = customer
        return True
