import random
from urllib.parse import urlencode
import requests
from django.contrib.auth.models import User
from rest_framework.views import APIView
from rest_framework.response import Response
from distributors.models import Distributors
from retailers.models import Retailer
from settings.models import AppDashboardMessage, Banners, Operator, MRobotics, ServiceCategory, State
from api.settings.serializers import (
    AppDashboardMessageSerializer,
    BannersSerializer,
    DistributorsSerializer,
    OperatorSerializer,
    MRoboticsSerializer,
    RetailerSerializer,
    ServiceCategorySerializer,
    StateSerializer,
)

class OperatorAPI(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request, id=0, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:
            data = []
            if id > 0:
                data = Operator.objects.filter(id=id)
            else:
                data = Operator.objects.filter(is_active=True)

            if len(data) > 0:
                __rslt["data"] = OperatorSerializer(data, many=True).data
                __rslt["ok"] = 1
            else:
                __rslt["error"] = "No Data Found!"

        except Exception as ex:
            __rslt["error"] = ex.args

        return Response(__rslt)

    def post(self, request, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:
            data = request.data
            serializer = OperatorSerializer(data=data)
            if serializer.is_valid():
                serializer.save()
                __rslt["ok"] = 1
                __rslt["data"] = data

        except Exception as ex:
            __rslt["error"] = ex.args

        return Response(__rslt)


class OperatorByServiceAPI(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request, service, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:
            data = []
            data = Operator.objects.filter(service__name__contains=service)

            if len(data) > 0:
                __rslt["data"] = OperatorSerializer(data, many=True).data
                __rslt["ok"] = 1
            else:
                __rslt["error"] = "No Data Found!"

        except Exception as ex:
            __rslt["error"] = ex.args

        return Response(__rslt)


class MRoboticsAPI(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request, id=0, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:
            data = []
            if id > 0:
                data = MRobotics.objects.filter(id=id)
            else:
                data = MRobotics.objects.filter(is_active=True)

            if len(data) > 0:
                __rslt["data"] = MRoboticsSerializer(data, many=True).data
                __rslt["ok"] = 1
            else:
                __rslt["error"] = "No Data Found!"

        except Exception as ex:
            __rslt["error"] = ex.args

        return Response(__rslt)

    def post(self, request, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:
            data = request.data
            serializer = MRoboticsSerializer(data=data)
            if serializer.is_valid():
                serializer.save()
                __rslt["ok"] = 1
                __rslt["data"] = data

        except Exception as ex:
            __rslt["error"] = ex.args

        return Response(__rslt)


class StateAPI(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request, id=0, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:
            data = []
            if id > 0:
                data = State.objects.filter(id=id)
            else:
                data = State.objects.filter(is_active=True)

            if len(data) > 0:
                __rslt["data"] = StateSerializer(data, many=True).data
                __rslt["ok"] = 1
            else:
                __rslt["error"] = "No Data Found!"

        except Exception as ex:
            __rslt["error"] = ex.args

        return Response(__rslt)


class OTPAPI(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request, number, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:

            api = "AXD9pnkt3CBRydl4eiNIPVbxJv6YSjwoa1TGH8Wuf0LQ7Zqshm3gncO1obJHyZQef0Aikqr2PSVWwE5j="
            otp = "".join(random.choices("0123456789", k=4))

            myData = {
                "authorization": api,
                "variables_values": otp,
                "route": "otp",
                "numbers": number,
            }

            query_string = urlencode(myData)

            new_api = 'bc9d3aa7-f68b-11f0-a6b2-0200cd936042'

            # url = f"https://www.fast2sms.com/dev/bulkV2?{query_string}"
            # response = requests.get(url)

            url = f"https://2factor.in/API/V1/{new_api}/SMS/+91{number}/{otp}/OTP1"

            payload={}
            headers = {}

            response = requests.request("GET", url, headers=headers, data=payload)

            print(response.text)

            __rslt["data"] = response.json()

            if response.status_code == 200:
                __rslt["data"] = {"otp": otp, "data": response.json()}
                __rslt["ok"] = 1
            else:
                __rslt["error"] = "Something Went wrong!"

        except Exception as ex:
            __rslt["error"] = ex.args

        return Response(__rslt)


class ServiceAPI(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:
            data = []
            data = ServiceCategory.objects.filter(is_active=True)

            if len(data) > 0:
                __rslt["data"] = ServiceCategorySerializer(data, many=True).data
                __rslt["ok"] = 1
            else:
                __rslt["error"] = "No Data Found!"

        except Exception as ex:
            __rslt["error"] = ex.args

        return Response(__rslt)


class DistributorsAPI(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request, username, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:
            data = []
            usr = User.objects.get(username=username)
            if usr.is_superuser:
                data = Distributors.objects.filter(is_active=True)
            else:
                data = Distributors.objects.filter(
                    super_distributor__user__username=username
                )

            if len(data) > 0:
                __rslt["data"] = DistributorsSerializer(data, many=True).data
                __rslt["ok"] = 1
            else:
                __rslt["error"] = "No Data Found!"

        except Exception as ex:
            __rslt["error"] = ex.args

        return Response(__rslt)


class RetailersAPI(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request, username, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:
            data = []
            data = Retailer.objects.filter(distributor__user__username=username)

            if len(data) > 0:
                __rslt["data"] = RetailerSerializer(data, many=True).data
                __rslt["ok"] = 1
            else:
                __rslt["error"] = "No Data Found!"

        except Exception as ex:
            __rslt["error"] = ex.args

        return Response(__rslt)


class BannersAPI(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:
            data = []
            
            data = Banners.objects.filter(is_active=True)

            if len(data) > 0:
                __rslt["data"] = BannersSerializer(data, many=True).data
                __rslt["ok"] = 1
            else:
                __rslt["error"] = "No Data Found!"

        except Exception as ex:
            __rslt["error"] = ex.args

        return Response(__rslt)



class MessageAPI(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request, format=None):
        __rslt = {"ok": 0, "message": "", "error": "", "data": None}
        try:
            data = []
            
            data = AppDashboardMessage.objects.filter(is_active=True).last()

            if data:
                __rslt["data"] = [AppDashboardMessageSerializer(data).data]
                __rslt["ok"] = 1
            else:
                __rslt["error"] = "No Data Found!"

        except Exception as ex:
            __rslt["error"] = ex.args

        return Response(__rslt)

