from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope
from rest_framework import viewsets
from rest_framework import status
from rest_framework.permissions import AllowAny
from rest_framework.response import Response

from LiveStock.Union.filterset import UnionFilterSet
from LiveStock.Union.serializers import UnionSerializer
from LiveStock.helpers import build_query, CustomPagination
from LiveStock.models import Union
from authentication.models import SystemUserProfile, City, Province, SystemAddress
from django.contrib.auth.models import User, Group

from authentication.views import ARTA_URL_REGISTER, ARTA_URL_CHANGE_MOBILE_NUMBER
from panel.admin import PROJECT_API_KEY
import requests


class UnionViewSet(viewsets.ModelViewSet):
    queryset = Union.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = UnionSerializer
    filterset_class = UnionFilterSet
    pagination_class = CustomPagination

    def retrieve(self, request, pk=None, *args, **kwargs):
        if 'profile' in request.GET:
            user = SystemUserProfile.objects.get(user=request.user, trash=False)

            union = user.union_user.all()

            serializer = self.serializer_class(union[0])
            return Response(serializer.data, status=status.HTTP_200_OK)

    def list(self, request, *args, **kwargs):
        unions = Union.objects.filter(trash=False).order_by('id')
        value = request.GET.get('value')
        search = request.GET.get('search')
        if value and search == 'filter':
            if search != 'undefined' and search.strip():
                unions = unions.filter(
                    build_query(self.filterset_class.Meta.fields, value)
                )
        page = self.paginate_queryset(unions)
        if page is not None:
            serializer = self.serializer_class(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.serializer_class(unions, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def create(self, request, *args, **kwargs):
        group = Group.objects.get(name__exact="Union")
        city = City.objects.get(name=request.data['city'])
        request.data.pop('city')
        province = Province.objects.get(key=city.province.key)
        system_profile = SystemUserProfile.objects.filter(mobile=request.data['mobile'], trash=False).last()
        if system_profile:
            if Union.objects.filter(user=system_profile, trash=False).exists():
                return Response({"result": "این اتحادیه قبلا ثبت شده است"}, status=status.HTTP_403_FORBIDDEN)

        else:
            password = "123456"
            data = {
                "username": request.data['mobile'],
                "password": password,
                "api_key": PROJECT_API_KEY
            }
            req = requests.post(
                url=ARTA_URL_REGISTER,
                data=data,
                verify=False
            )

            if req.status_code == 200:
                user = User(username=request.data['mobile'], first_name=request.data['first_name'],
                            last_name=request.data['last_name'])
                user.save()
                base_id = SystemUserProfile.objects.all()
                if base_id.count() > 0:
                    base_id = int(base_id.last().base_order) + 1
                else:
                    base_id = 1000
                system_profile = SystemUserProfile(
                    mobile=request.data['mobile'],
                    first_name=request.data['first_name'],
                    last_name=request.data['last_name'],
                    fullname=request.data['first_name'] + " " + request.data['last_name'],
                    user=user,
                    base_order=base_id,
                    password=password,
                    national_id=request.data['national_id'],
                    city=city,
                    province=province
                )
                system_profile.save()
            else:
                return Response({"result": "در ثبت کاربر مشکلی بوجود آمده است "}, status=status.HTTP_403_FORBIDDEN)
        address = SystemAddress(city=city, province=province, address=request.data['address'],
                                postal_code=request.data['postal_code'])
        address.save()
        system_profile.role.add(group)
        request.data.pop('first_name')
        request.data.pop('last_name')
        request.data.pop('address')
        request.data.pop('postal_code')
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            union = serializer.create(validated_data=request.data)
            union.user = system_profile
            union.address = address
            union.save()
            return Response({"result": "با موفقیت ثبت شد"}, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def update(self, request, pk=None, *args, **kwargs):
        union = Union.objects.get(key=request.data['union_key'], trash=False)
        address = SystemAddress.objects.get(key=union.address.key, trash=False)
        request.data.pop('union_key')
        if 'first_name' in request.data.keys():
            system_user_profile = SystemUserProfile.objects.get(key=union.user.key, trash=False)
            system_user_profile.first_name = request.data['first_name']
            system_user_profile.last_name = request.data['last_name']
            system_user_profile.fullname = request.data['first_name'] + " " + request.data['last_name']
            system_user_profile.save()
            first_mobile_number = system_user_profile.mobile
            second_mobile_number = request.data['mobile']
            if first_mobile_number != second_mobile_number:
                if SystemUserProfile.objects.filter(mobile=second_mobile_number).exists():
                    return Response({"result": "این شماره در سامانه به نام شخص دیگری است"},
                                    status=status.HTTP_403_FORBIDDEN)
                data = {
                    "first_mobile_number": first_mobile_number,
                    "second_mobile_number": second_mobile_number,
                }
                req = requests.post(
                    url=ARTA_URL_CHANGE_MOBILE_NUMBER,
                    data=data,
                    verify=False
                )
                if req.status_code == 200:
                    second_mobile_number = second_mobile_number
                    user = User.objects.get(id=system_user_profile.user.id)
                    user.username = second_mobile_number
                    user.save()
                    system_user_profile.mobile = second_mobile_number
                    system_user_profile.save()
            city = City.objects.get(name=request.data['city'])
            province = Province.objects.get(key=city.province.key)
            address.city = city
            address.province = province
            address.address = request.data['address']
            address.postal_code = request.data['postal_code']
            address.save()
            request.data.pop('first_name')
            request.data.pop('last_name')
            request.data.pop('address')
            request.data.pop('city')

        serializer = self.serializer_class(union)
        serializer.update(instance=union, validated_data=request.data)
        return Response(serializer.data, status=status.HTTP_200_OK)

    # def update(self, request, *args, **kwargs):
    #     union = Union.objects.get(key=request.data['key'], trash=False)
    #     request.data.pop('key')
    #     if 'city' in request.data:
    #         city_key=request.data['city']
    #         request.data.pop('city')
    #         city=City.objects.filter(key=city_key,trash=False).first()
    #         union.address.city=city
    #         union.address.save()
    #     serializer = self.serializer_class(union)
    #
    #     serializer.update(instance=union, validated_data=request.data)
    #     return Response(serializer.data, status=status.HTTP_200_OK)

    def destroy(self, request, pk=None, *args, **kwargs):
        union = Union.objects.get(key=request.GET["key"])
        union.trash = True
        union.save()
        return Response({"result": "با موفقیت حذف شد"}, status=status.HTTP_200_OK)
