from oauth2_provider.contrib.rest_framework import TokenHasReadWriteScope
from rest_framework import viewsets
from rest_framework import status
from rest_framework.response import Response
import requests
from django.contrib.auth.models import User, Group

from LiveStock.Cooperative.filterset import CooperativeFilterSet
from LiveStock.Cooperative.serializers import CooperativeSerializer, CooperativeForAllocationsReportSerializer
from LiveStock.helpers import build_query, CustomPagination
from LiveStock.models import Cooperative, CooperativeProductsShare, LiveStockProduct, LiveStockRolseProduct
from authentication.models import SystemUserProfile, City, Province, SystemAddress
from authentication.views import ARTA_URL_CHANGE_MOBILE_NUMBER, ARTA_URL_REGISTER
from panel.admin import PROJECT_API_KEY


class CooperativeViewSet(viewsets.ModelViewSet):
    queryset = Cooperative.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = CooperativeSerializer
    filterset_class = CooperativeFilterSet
    pagination_class = CustomPagination

    def create(self, request, *args, **kwargs):
        group = Group.objects.get(name__exact="Cooperative")
        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 Cooperative.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')
        products = LiveStockProduct.objects.filter(trash=False)
        serializer = self.serializer_class(data=request.data)
        if serializer.is_valid():
            cooperative = serializer.create(validated_data=request.data)
            cooperative.user = system_profile
            cooperative.address = address
            cooperative.save()
            for product in products:
                share = CooperativeProductsShare(
                    cooperative=cooperative,
                    product=product
                )
                share.save()
                cooperative_roles_product = LiveStockRolseProduct(
                    cooperative=cooperative,
                    parent_product=product

                )
                cooperative_roles_product.save()
            return Response({"result": "با موفقیت ثبت شد"}, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

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

            cooperative = user.cooperative_user.all()

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

    def list(self, request, *args, **kwargs):
        cooperatives = Cooperative.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():
                cooperatives = cooperatives.filter(
                    build_query(self.filterset_class.Meta.fields, search)
                )
        page = self.paginate_queryset(cooperatives)
        if page is not None:
            serializer = self.serializer_class(page, many=True)
            return self.get_paginated_response(serializer.data)
        serializer = self.serializer_class(cooperatives, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def update(self, request, pk=None, *args, **kwargs):
        cooperative = Cooperative.objects.get(key=request.data['cooperative_key'], trash=False)
        address = SystemAddress.objects.get(key=cooperative.address.key, trash=False)
        request.data.pop('cooperative_key')
        if 'first_name' in request.data.keys():
            system_user_profile = SystemUserProfile.objects.get(key=cooperative.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(cooperative)
        serializer.update(instance=cooperative, validated_data=request.data)
        return Response(serializer.data, status=status.HTTP_200_OK)


class CooperativeWarehouseDashboardViewSet(viewsets.ModelViewSet):
    queryset = Cooperative.objects.all()
    permission_classes = [TokenHasReadWriteScope]
    serializer_class = CooperativeForAllocationsReportSerializer
    filterset_class = CooperativeFilterSet
    pagination_class = CustomPagination

    def list(self, request, *args, **kwargs):
        cooperatives = Cooperative.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():
                cooperatives = cooperatives.filter(
                    build_query(self.filterset_class.Meta.fields, search)
                )
        page = self.paginate_queryset(cooperatives)
        if page is not None:
            serializer = self.serializer_class(page, many=True,context={"request":request})
            return self.get_paginated_response(serializer.data)
        serializer = self.serializer_class(cooperatives, many=True,context={"request":request})
        return Response(serializer.data, status=status.HTTP_200_OK)
