import requests
from .models import Gotv, Config
from base64 import b64encode
import random
from datetime import datetime
import uuid
import json


# GOTV 

# VTPASS GOTV FUNCTION
def gotv_vtpass(service, plan, iuc_number, user):
    global new_bal, plan_id, price
    def request_id():
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")
        num = random.randint(10000000, 99999999)
        random_num = str(num)
        request_idd = the_date + random_num
        return request_idd

    request_id = request_id()
    tv = Gotv.objects.get(package=plan)
    # vtpass_key = table.vtpass_api_key.encode()
    # vtpass_api_key = b64encode(vtpass_key).decode()


    url = "https://api-service.vtpass.com/api/pay"
    parameters = {
        "request_id": request_id,
        "billersCode": int(iuc_number),
        "serviceID": "gotv",
        "variation_code": tv.vtpass_code,
        "phone": int(user.phoneNumber),
        "subscription_type": "change"
    }
    # headers = {
    #     "Authorization": f"Basic {vtpass_api_key}",
    #     "Content-Type": "application/json",
    # }
    
    headers = {
          'Content-Type':'application/json',
          "api-key": "37cbf73ed25cf7eadcc90868ad9ca279",
          "secret-key": "SK_871c545f322d2689c0d02f660e462715ed36771474f",
         }

    responses = requests.post(url, headers=headers, json=parameters)
    response = responses.json()
    if response:
        description = response["response_description"]
        if description == "TRANSACTION SUCCESSFUL":
            result = [f"Successful {description}", "Successful", request_id]
            return result
        elif description == "TRANSACTION FAILED" or description == "LOW WALLET BALANCE":
            result = [f" Oops {description}", "Unsuccessful", request_id]
            return result
        else:
            result = [(
                f"Pending, dear customer, your transaction is pending, you can confirm if "
                f"the service has being delivered or contact admin"), "Pending", request_id]
            return result
    else:
        result = [(
            f"Pending, dear customer, your transaction is pending, you can confirm if the "
            f"service has being delivered or contact admin"), "Pending", request_id]
        return result



# MERRYBILLS GOTV FUNCTION
def gotv_merrybills(service, plan, iuc_number, user):

    global plan_id, price

    def request_id():

        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")

        num = random.randint(10000000, 99999999)
        random_num = str(num)

        request_idd = the_date + random_num

        return request_idd

    request_id = request_id()

    table = Config.objects.get(pk=1)
    merrykey = table.merrybills_api_key

    tv = Gotv.objects.get(package=plan)

    url = "https://merrybills.com/api/v2/cable"

    parameters = {
        "request_id": request_id,
        "iuc_number": iuc_number,
        "product_id": "m43Ru6Jz9i",
        "variation": tv.merrybills_code,
        "type": "change",
        "month": 1,
        "pin": "4734",
    }

    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "Authorization": f"Bearer {merrykey}",
    }

    try:

        responses = requests.post(
            url,
            headers=headers,
            json=parameters
        )

        response = responses.json()

        print(response)

        if response:

            status = response["data"]["transaction"]["status"]

            if status == "completed":

                description = response["data"]["transaction"]["details"]

                result = [
                    f"Successful {description}.",
                    "Successful",
                    request_id
                ]

                return result

            elif status == "processing":

                result = [
                    "Oops Your transaction is processing",
                    "Pending",
                    request_id
                ]

                return result

            elif status == "refund":

                result = [
                    "Oops Transaction Unsuccessful",
                    "Unsuccessful",
                    request_id
                ]

                return result

            else:

                # Unknown provider status.
                # The actual transaction result is not confirmed.
                result = [
                    "Transaction status is currently unavailable. Please confirm your transaction status or contact support.",
                    "Pending",
                    request_id
                ]

                return result

        else:

            result = [
                "Pending, dear customer, your transaction is pending, you can confirm if the service has being delivered or contact admin",
                "Pending",
                request_id
            ]

            return result

    except Exception as e:

        # The provider result is unknown.
        # Do not automatically refund the customer.

        print("GOtv MerryBills error:", e)

        result = [
            "Transaction is pending. Please confirm your transaction status or contact support.",
            "Pending",
            request_id
        ]

        return result


def gotv_apisub(service, plan, iuc_number, user):

    def request_id():

        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")

        num = random.randint(10000000, 99999999)
        random_num = str(num)

        request_idd = the_date + random_num

        return request_idd

    request_id = request_id()

    table = Config.objects.get(pk=1)
    apisubportal_key = table.apisubportal_key

    tv = Gotv.objects.get(package=plan)

    url = "https://apisubportal.com/api/buycable.php"

    parameters = {
        "api_key": apisubportal_key,
        "service": "GOTV",
        "return_url": "yarabpro.com",
        "package": tv.apisub_code,
        "number": iuc_number,
    }

    try:

        responses = requests.get(
            url,
            params=parameters
        )

        response = json.loads(responses.text)

    except Exception as e:

        print("GOtv API Sub error:", e)

        result = [
            "Transaction is pending. Please confirm your transaction status or contact support.",
            "Pending",
            request_id
        ]

        return result

    try:

        res = response["status"]

    except (KeyError, TypeError):

        # The provider response does not contain a recognizable status.
        result = [
            "Transaction status is currently unavailable. Please confirm your transaction status or contact support.",
            "Pending",
            request_id
        ]

        return result

    if res == "success":

        result = [
            "Successful GOTV Subscription",
            "Successful",
            request_id
        ]

        return result

    elif res == "unsuccessful":

        result = [
            "Oops unsuccessful GOTV Subscription",
            "Unsuccessful",
            request_id
        ]

        return result

    else:

        # Unknown provider status.
        # Do not automatically refund the customer.
        result = [
            "Transaction status is currently unavailable. Please confirm your transaction status or contact support.",
            "Pending",
            request_id
        ]

        return result


# AUTOPILOT GOTV FUNCTION
def gotv_autopilot(service, plan, iuc_number, user):
    def request_id_gen():
        # Request ID generator
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")
        tok = uuid.uuid4()
        token = tok.hex
        req = the_date + token
        request_id = req[0:25]
        return request_id
    request_id = request_id_gen()

    table = Config.objects.get(pk=1)
    autopilot_key = table.autopilot_key

    tv = Gotv.objects.get(package=plan)

    url = "https://autopilotng.com/api/live/v1/cable"
    url2 = "https://autopilotng.com/api/live/v1/validate/smartcard-no"

    payload2 = {
        "cableType": "GOTV",
        "smartCardNo": iuc_number,
    }

    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "Authorization": f"Bearer {autopilot_key}",
    }

    validator = requests.post(url2, headers=headers, json=payload2)
    try:
        dat = validator.json()
        customer_name = dat["data"]["validate"]["customerName"]
    except:
        customer_name = ""

    payload = {
        "cableType": "GOTV",
        "planId": tv.autopilot_code,
        "paymentTypes": "FULL_PAYMENT",
        "customerName": customer_name,
        "smartCardNo": iuc_number,
        "reference": request_id
    }

    try:
        resp = requests.post(url, headers=headers, json=payload)
        response = resp.json()
        if 'code' in response:
            stat = response['code']
            if stat == 200:
                status = 'successful'
                api = response['data']['message']
            elif stat == 201:
                status = 'processing'
                api = response['data']['message']
            else:
                status = 'failed'
                api = response['data']['message']
        else:
            status = 'processing'
            api = 'processing'

        if status == "successful":
            result = [f"Successful {api}", "Successful", request_id]
            return result
        elif status == "processing":
            result = [f"Pending, {api}", "Pending", request_id]
            return result
        elif status == "failed":
            result = [f" Oops Unsuccessful {api}", "Unsuccessful", request_id]
            return result
        else:
            result = ["Transaction unsuccessful", "Unsuccessful", request_id]
            return result

    except:
        result = [(
            f"Pending, dear customer, your transaction is pending, you can confirm if the "
            f"service has being delivered or contact admin"), "Pending", request_id]
        return result



def gotv_ringo(service, plan, iuc_number, user):

    def request_id_gen():

        # Request ID generator
        date_time = datetime.now()
        the_date = date_time.strftime("%Y%m%d%H%M")

        tok = uuid.uuid4()
        token = tok.hex

        req = the_date + token
        request_id = req[0:25]

        return request_id

    request_id = request_id_gen()

    table = Config.objects.get(pk=1)

    email = table.ringo_email
    password = table.ringo_password

    tv = Gotv.objects.get(package=plan)

    url = "https://www.api.ringo.ng/api/agent/p2"

    payload = {
        "serviceCode": "P-TV",
        "type": "GOTV",
        "code": tv.ringo_code,
        # "hasAddon": "False",
        "name": tv.ringo_name,
        "smartCardNo": iuc_number,
        "request_id": request_id,
        "period": "1"
    }

    headers = {
        "Content-Type": "application/json",
        "email": email,
        "password": password,
    }

    try:

        responses = requests.post(
            url,
            headers=headers,
            json=payload
        )

        response = responses.json()

        print(response)

        if 'status' in response:

            stat = response['status']

            if stat == '200':

                status = 'successful'

                api = response.get(
                    'message',
                    'Transaction Successful'
                )

            elif stat == '201':

                status = 'processing'

                api = response.get(
                    'message',
                    'Transaction is processing'
                )

            else:

                status = 'failed'

                api = response.get(
                    'message',
                    'Transaction Failed'
                )

        else:

            status = 'processing'

            api = 'Transaction status is currently unavailable'

    except Exception as e:

        # An exception does not necessarily mean that
        # Ringo rejected the transaction.
        #
        # The provider may have received/processed the
        # request before the connection or response failed.
        #
        # Therefore, keep the transaction Pending instead
        # of automatically refunding the customer.

        print("GOtv Ringo error:", e)

        status = 'processing'

        api = "Transaction is pending. Please confirm your transaction status or contact support."

    if status == "successful":

        result = [
            f"Successful {service} {api}",
            "Successful",
            request_id
        ]

        return result

    elif status == "processing":

        result = [
            f"Pending, {service} {api}",
            "Pending",
            request_id
        ]

        return result

    elif status == "failed":

        result = [
            f"Oops Unsuccessful {service}, {api}",
            "Unsuccessful",
            request_id
        ]

        return result

    else:

        result = [
            "Transaction unsuccessful",
            "Unsuccessful",
            request_id
        ]

        return result