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



# STARTIMES 


#   VTPASS STARTIMES FUNCTION
def startimes_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 = Startimes.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": "startimes",
        "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 startimes FUNCTION
def startimes_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 = Startimes.objects.get(package=plan)

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

    parameters = {
        "request_id": request_id,
        "iuc_number": iuc_number,
        "product_id": "DW1dC3jrWS",
        "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("StarTimes MerryBills error:", e)

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

        return result

def startimes_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 = Startimes.objects.get(package=plan)

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

    parameters = {
        "api_key": apisubportal_key,
        "service": "STARTIMES",
        "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("StarTimes 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 STARTIMES Subscription",
            "Successful",
            request_id
        ]

        return result

    elif res == "unsuccessful":

        result = [
            "Oops unsuccessful STARTIMES 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
        
        
def startimes_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 = Startimes.objects.get(package=plan)

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

    payload = {
        "serviceCode": "P-TV",
        "type": "STARTIMES",
        "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 or processed the
        # request before the connection or response failed.
        #
        # Therefore, keep the transaction Pending instead
        # of automatically refunding the customer.

        print("StarTimes 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