from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework import status
from django.views.decorators.csrf import csrf_exempt

from general_urls import BASE_URL
from .ProvinceOperator.serializers import POSAccessLevelSerializer
from .models import POSMachine, RolesProducts, PosDeviceVersion, POSAccessLevel
import requests
from requests.exceptions import RequestException

from .validate_headers import PosDeviceValidator


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def Check_server(request):
    data = {"server": [
        {
            "key": "Test",
            "name": "تست",
            "address": "https://testbackend.rasadyar.com"
        },
        {
            "key": "Hamedan",
            "name": "همدان",
            "address": "https://habackend.rasadyar.com"
        },
        {
            "key": "Markazi",
            "name": "مرکزی",
            "address": "https://mabackend.rasadyar.com"
        }
    ]
    }
    return Response(data, status=status.HTTP_200_OK)

@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def pos_finder(request):
    validator = PosDeviceValidator(request)
    validation_error = validator.validation_version()
    if validation_error:
        return validation_error

    validation_device = validator.validation_device()
    if not validation_device:
        return Response({"result": "نشست شما منقضی شده لطفا محدد وارد شوید!"}, status=status.HTTP_401_UNAUTHORIZED)

    pos_machine = (
        POSMachine.objects
            .select_related('user__province')
            .only('pos_id', 'user__fullname', 'user__province__name')
            .filter(pos_id=validation_device)
    )
    if not pos_machine.exists():
        return Response({"result": "صنفی با این شناسه یافت نشد!"}, status=status.HTTP_404_NOT_FOUND)
    url = BASE_URL.replace('api/', '')
    pos_machine = pos_machine.first()
    version = PosDeviceVersion.objects.filter(company=pos_machine.pos_company).order_by('code').last()
    name=version.name if version else None
    code=version.code if version else None
    link=version.link if version else None
    checksum=version.checksum if version else None
    if pos_machine.guild:
        store_name = pos_machine.guild.guilds_name
        phone = pos_machine.guild.phone
        key = pos_machine.guild.key
        type_activity = pos_machine.guild.type_activity
        area_activity = pos_machine.guild.area_activity
        seller_type = "Guild" if pos_machine.guild.steward == False else "Steward"
        product = RolesProducts.objects.filter(guild=pos_machine.guild, trash=False, name='مرغ گرم').first()
        product_name = product.parent_product.name if product else None
        product_image = product.parent_product.image if product else None
        product_key = product.key if product else None
        other_product = True




    elif pos_machine.cooperative:
        store_name = pos_machine.cooperative.name
        phone = pos_machine.cooperative.mobile
        key = pos_machine.cooperative.key
        seller_type = "cooperative"
        type_activity = "تعاونی"
        area_activity = "تعاونی"
        product_name = None
        product_image = None
        product_key = None
        other_product = True
    else:
        store_name = pos_machine.kill_house.name
        phone = pos_machine.kill_house.phone
        key = pos_machine.kill_house.key
        seller_type = "KillHouse"
        type_activity = "کشتارگاه"
        area_activity = "کشتارگاه"
        product = RolesProducts.objects.filter(kill_house=pos_machine.kill_house, trash=False, name='مرغ گرم').first()
        product_name = product.parent_product.name if product else None
        product_image = product.parent_product.image if product else None
        product_key = product.key if product else None
        other_product = True

    data = {
        "type": seller_type,
        "name": store_name,
        "type_activity": type_activity,
        "area_activity": area_activity,
        "phone": phone,
        "mobile": pos_machine.user.mobile,
        "fullname": pos_machine.user.fullname,
        "firstname": pos_machine.user.first_name,
        "lastname": pos_machine.user.last_name,
        "city": pos_machine.user.city.name,
        "province": pos_machine.user.province.name,
        "national_code": pos_machine.user.national_code,
        "national_id": pos_machine.user.national_id,
        "birthday": pos_machine.user.birthday,
        "url": url,
        "key": key,
        "server": "Test",
        "segmentation": True,
        "product_name": product_name,
        "product_image": product_image,
        "product_key": product_key,
        "other_product": other_product,
        "version_name": name,
        "code": code,
        "link": link,
        "checksum": checksum,

    }
    return Response(data, status=status.HTTP_200_OK)


@api_view(["GET"])
@csrf_exempt
@permission_classes([AllowAny])
def pos_get_finder(request):
    pos_id = request.GET.get('pos-id')
    if not pos_id:
        return Response({"result": "شناسه POS مشخص نشده است!"}, status=status.HTTP_400_BAD_REQUEST)

    pos_machine = (
        POSMachine.objects
            .select_related('user__province')
            .only('pos_id', 'user__fullname', 'user__province__name')
            .filter(pos_id=pos_id)
    )
    if not pos_machine.exists():
        return Response({"result": "صنفی با این شناسه یافت نشد!"}, status=status.HTTP_404_NOT_FOUND)
    url = BASE_URL.replace('api/', '')
    pos_machine = pos_machine.first()
    if pos_machine.guild:
        store_name = pos_machine.guild.guilds_name
        phone = pos_machine.guild.guilds_name
        key = pos_machine.guild.key
        seller_type = "Guild" if pos_machine.guild.steward == False else "Steward"


    elif pos_machine.cooperative:
        store_name = pos_machine.cooperative.name
        phone = pos_machine.cooperative.mobile
        key = pos_machine.cooperative.key
        seller_type = "cooperative"


    else:
        store_name = pos_machine.kill_house.name
        phone = pos_machine.kill_house.phone
        key = pos_machine.kill_house.key
        seller_type = "KillHouse"
    data = {
        "type": seller_type,
        "name": store_name,
        "phone": phone,
        "mobile": pos_machine.user.mobile,
        "fullname": pos_machine.user.fullname,
        "firstname": pos_machine.user.first_name,
        "lastname": pos_machine.user.last_name,
        "city": pos_machine.user.city.name,
        "province": pos_machine.user.province.name,
        "national_code": pos_machine.user.national_code,
        "national_id": pos_machine.user.national_id,
        "birthday": pos_machine.user.birthday,
        "url": url,
        "key": key,
        "server": "Test",
    }
    return Response(data, status=status.HTTP_200_OK)


@api_view(["POST"])
@csrf_exempt
@permission_classes([AllowAny])
def pos_login(request):
    validator = PosDeviceValidator(request)
    validation_error = validator.validation_version()
    if validation_error:
        return validation_error

    pos_machine = validator.manage_device()

    if not pos_machine.owner:
        return Response({"result": f"برای این دستگاه مالکی تعیین نشده!شناسه پوز:{pos_machine.pos_unique_id}"},
                        status=status.HTTP_403_FORBIDDEN)

    if not pos_machine.active:
        return Response({"result": f"دستگاه غیر فعال میباشد!شناسه پوز:{pos_machine.pos_unique_id}"},
                        status=status.HTTP_403_FORBIDDEN)
    url = BASE_URL.replace('api/', '')
    version = PosDeviceVersion.objects.filter(company=pos_machine.pos_company).order_by('code').last()
    name = version.name if version else None
    code = version.code if version else None
    link = version.link if version else None
    checksum = version.checksum if version else None
    access_levels = POSAccessLevel.objects.filter(pos=pos_machine)
    access_levels = POSAccessLevelSerializer(access_levels,many=True).data
    agent = True if (pos_machine.current_user or pos_machine.current_representative) else False
    agent_fullname =None
    agent_mobile =None
    agent_type =None
    if agent:
        if pos_machine.current_user:
            agent_fullname = pos_machine.current_user.fullname
            agent_mobile = pos_machine.current_user.mobile
            agent_type = 'dispenser'

        else:
            agent_fullname = pos_machine.current_representative.first_name + "" +pos_machine.current_representative.last_name
            agent_mobile = pos_machine.current_representative.mobile
            agent_type = 'representative'

    data = {
        "mobile": pos_machine.owner.mobile,
        "fullname": pos_machine.owner.fullname,
        "firstname": pos_machine.owner.first_name,
        "lastname": pos_machine.owner.last_name,
        "city": pos_machine.owner.city.name,
        "province": pos_machine.owner.province.name,
        "national_code": pos_machine.owner.national_code,
        "national_id": pos_machine.owner.national_id,
        "birthday": pos_machine.owner.birthday,
        "url": url,
        "key": pos_machine.key,
        "server": "Markazi",
        "pos_unique_id": pos_machine.pos_unique_id,
        "version_name": name,
        "code": code,
        "link": link,
        "checksum": checksum,
        "access_levels": access_levels,
        "agent": agent,
        "agent_type": agent_type,
        "agent_fullname": agent_fullname,
        "agent_mobile": agent_mobile,

    }
    return Response(data, status=status.HTTP_200_OK)
