import requests
from .models import Airtelawoofgifting, Config, mailer
import random
from datetime import datetime
import uuid
import json


# AIRTEL CG_______


def manual_airtelawoof(network, plan, phone):
    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()
    

    try:
        send_telegram_notification(f'Dear Admin, sell {plan.volume} {network} on {phone}.')
        # mailer(email, f'{network} MANUAL',
        #       f'Dear Admin, sell {plan.volume} {network} on {phone}.')
        result = [f"Successful {plan.volume} {network} on {phone}. The activation of {plan.volume} {network} was successful.", "Successful", request_id]
        return result
    except:
        result = [f" Oops Transaction Unsuccessful", "Unsuccessful", request_id]
        return result

def plan_code(network, plan, phone):
    
    sell = globals()[plan.vending_medium](network, plan, phone)
    
    return sell


def autopilot_airtelawoof(network, plan, phone):
    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

    url = "https://autopilotng.com/api/live/v1/data"
    payload = {
        "networkId": "2",
        "dataType": "AWOOF GIFTING",
        "planId": plan.autopilot_id,
        "phone": phone,
        "reference": request_id
    }

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

    }
    try:
        responses = requests.post(url, headers=headers, json=payload)
        response = responses.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'
    except:
        status = 'failed'
        api = "Transaction Failed"

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





def ms_airtelawoof(network, plan, phone):
    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)
    ms_url = table.ms_url
    ms_api_key = table.ms_api_key

    url = f"{ms_url}/api/data/"
    payload = {
        "network": "4",
        "plan": plan.ms_id,
        "mobile_number": phone,
        "Ported_number":True
    }

    headers = {
        'Content-Type':'application/json',
        'Authorization': f'Token {ms_api_key}'
    }
  
    try:
        responses = requests.post(url, headers=headers, json=payload)
        response = responses.json()
        
        if responses.status_code == 200 or responses.status_code == 201:
            if "Status" in response and response["Status"]  == "successful" :
                status = 'successful'
                if "api_response" in response:
                    api = response["api_response"]
                else:
                    api = "Transaction successful"
            elif "Status" in response and response["Status"]  == "processing":
                status = 'processing'
                api = 'Transaction processing'
            else:
                status = 'failed'
                api = "Transaction Failed"
        else:
            status = 'failed'
            api = "Transaction Failed"
    except:
        status = 'failed'
        api = "Transaction Failed"
        
        
    if status == "successful":
        result = [f"Successful {network}  {api}", "Successful", request_id]
        return result
    elif status == "processing":
        result = [f"Pending, {network}  {api}", "Pending", request_id]
        return result
    elif status == "failed":
        result = [f" Oops Unsuccessful {network},  {api}", "Unsuccessful", request_id]
        return result
    else:
        result = ["Transaction unsuccessful", "Unsuccessful", request_id]
        return result
  
                
        
def apisub_airtelawoof(network, plan, phone):
    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

    url = "https://apisubportal.com/api/buydata.php"
    parameters = {
        "api_key": apisubportal_key,
        "network": 'AIRTEL_AWOOF_DATA',
        "return_url": "yarabpro.com",
        "plans": plan.apisubportal_plan_id,
        "phonenumber": phone,
    }

    try:
        responses = requests.get(url, params=parameters)
        response = json.loads(responses.text)
    except:
        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

    res = response["status"]

    if res == "success":
        description = response["msg"]
        result = [f"Successful {network}  {description}", "Successful", request_id]
        return result

    elif res == "unsuccessful":
        description = response["msg"]
        result = [f" Oops  {network} {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



def atuns_airtelawoof(network, plan, phone):
    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)
    
    Atuns_web_api_key = table.Atuns_web_api_key
    Atuns_web_url = table.Atuns_web_url

    url = f"{Atuns_web_url}/api/data/"
    payload = {
        "network": "4",
        "plan": plan.Atuns_web_id,
        "mobile_number": phone,
        "Ported_number":True
    }

    headers = {
        'Content-Type':'application/json',
        'Authorization': f'Token {Atuns_web_api_key}'
    }
  
    try:
        responses = requests.post(url, headers=headers, json=payload)
        response = responses.json()
        
        if responses.status_code == 200 or responses.status_code == 201:
            if "Status" in response and response["Status"]  == "successful" :
                status = 'successful'
                if "api_response" in response:
                    api = response["api_response"]
                else:
                    api = "Transaction successful"
            elif "Status" in response and response["Status"]  == "processing":
                status = 'processing'
                api = 'Transaction processing'
            else:
                status = 'failed'
                api = "Transaction Failed"
        else:
            status = 'failed'
            api = "Transaction Failed"
    except:
        status = 'failed'
        api = "Transaction Failed"
        
        
    if status == "successful":
        result = [f"Successful {network}  {api}", "Successful", request_id]
        return result
    elif status == "processing":
        result = [f"Pending, {network}  {api}", "Pending", request_id]
        return result
    elif status == "failed":
        result = [f" Oops Unsuccessful {network},  {api}", "Unsuccessful", request_id]
        return result
    else:
        result = ["Transaction unsuccessful", "Unsuccessful", request_id]
        return result


def ms2_airtelawoof(network, plan, phone):
    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)

    url = f"{table.ms_url_2}/api/data/"
    payload = {
        "network": "4",
        "plan": plan.ms_id_2,
        "mobile_number": phone,
        "Ported_number":True
    }

    headers = {
        'Content-Type':'application/json',
        'Authorization': f'Token {table.ms_api_key_2}'
    }
  
    try:
        responses = requests.post(url, headers=headers, json=payload)
        response = responses.json()
        
        if responses.status_code == 200 or responses.status_code == 201:
            if "Status" in response and response["Status"]  == "successful" :
                status = 'successful'
                if "api_response" in response:
                    api = response["api_response"]
                else:
                    api = "Transaction successful"
            elif "Status" in response and response["Status"]  == "processing":
                status = 'processing'
                api = 'Transaction processing'
            else:
                status = 'failed'
                api = "Transaction Failed"
        else:
            status = 'failed'
            api = "Transaction Failed"
    except:
        status = 'failed'
        api = "Transaction Failed"
        
        
    if status == "successful":
        result = [f"Successful {network}  {api}", "Successful", request_id]
        return result
    elif status == "processing":
        result = [f"Pending, {network}  {api}", "Pending", request_id]
        return result
    elif status == "failed":
        result = [f" Oops Unsuccessful {network},  {api}", "Unsuccessful", request_id]
        return result
    else:
        result = ["Transaction unsuccessful", "Unsuccessful", request_id]
        return result



def ms3_airtelawoof(network, plan, phone):
    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)

    url = f"{table.ms_url_3}/api/data/"
    payload = {
        "network": "4",
        "plan": plan.ms_id_3,
        "mobile_number": phone,
        "Ported_number":True
    }

    headers = {
        'Content-Type':'application/json',
        'Authorization': f'Token {table.ms_api_key_3}'
    }
  
    try:
        responses = requests.post(url, headers=headers, json=payload)
        response = responses.json()
        
        if responses.status_code == 200 or responses.status_code == 201:
            if "Status" in response and response["Status"]  == "successful" :
                status = 'successful'
                if "api_response" in response:
                    api = response["api_response"]
                else:
                    api = "Transaction successful"
            elif "Status" in response and response["Status"]  == "processing":
                status = 'processing'
                api = 'Transaction processing'
            else:
                status = 'failed'
                api = "Transaction Failed"
        else:
            status = 'failed'
            api = "Transaction Failed"
    except:
        status = 'failed'
        api = "Transaction Failed"
        
        
    if status == "successful":
        result = [f"Successful {network}  {api}", "Successful", request_id]
        return result
    elif status == "processing":
        result = [f"Pending, {network}  {api}", "Pending", request_id]
        return result
    elif status == "failed":
        result = [f" Oops Unsuccessful {network},  {api}", "Unsuccessful", request_id]
        return result
    else:
        result = ["Transaction unsuccessful", "Unsuccessful", request_id]
        return result



def quicksim_airtelawoof(network, plan, phone):
    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()
    url = "https://quicklysim.com/msorg/api/data/"
    payload = {
        "network": "2",
        "plan": plan.quicksim_plan_id,
        "mobile_number": phone,
        "Ported_number":True
    }

    headers = {
        'Content-Type':'application/json',
        'Authorization': f'Token eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwczovL3F1aWNrbHlzaW0uY29tL2xpdmV3aXJlL3VwZGF0ZSIsImlhdCI6MTc1NjIxNzI1NywiZXhwIjoxNzg3NzUzMjU3LCJuYmYiOjE3NTYyMTcyNTcsImp0aSI6Ilc0aU9KSWFrbzlWeFFkeEQiLCJzdWIiOiIyOTUiLCJwcnYiOiIyM2JkNWM4OTQ5ZjYwMGFkYjM5ZTcwMWM0MDA4NzJkYjdhNTk3NmY3In0.criryJ99rW_0bdts-FwU7A2ej7FqLl4vaWECSRoFRu8'
    }
  
    try:
        responses = requests.post(url, headers=headers, json=payload)
        response = responses.json()
        print(response)
        
        if responses.status_code == 200 or responses.status_code == 201:
            if "Status" in response and response["Status"]  == "successful" :
                status = 'successful'
                if "api_response" in response:
                    api = response["api_response"]
                else:
                    api = "Transaction successful"
            elif "Status" in response and response["Status"]  == "processing":
                status = 'processing'
                api = 'Transaction processing'
            else:
                status = 'failed'
                if "api_response" in response:
                    api = response["api_response"]
                else:
                    api = "Transaction failed"
        else:
            status = 'failed'
            api = "Transaction Failed"
    except:
        status = 'failed'
        api = "Transaction Failed"
        
        
    if status == "successful":
        result = [f"Successful {network}  {api}", "Successful", request_id]
        return result
    elif status == "processing":
        result = [f"Pending, {network}  {api}", "Pending", request_id]
        return result
    elif status == "failed":
        result = [f" Oops Unsuccessful {network},  {api}", "Unsuccessful", request_id]
        return result
    else:
        result = ["Transaction unsuccessful", "Unsuccessful", request_id]
        return result



def pluginng_airteltalkmore(network, plan, phone):
    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)
    url = "https://pluginng.com/api/login"
    payload ={
    "email": table.pluginng_email,
    "password": table.pluginng_password
    }
    
    
    try:
        resp = requests.post(url, json=payload)
        rep = resp.json()
        token = rep["data"]["token"]
    except:
        token = ""

    headers = {
    'Content-Type':'application/json',
    'Authorization': f'Bearer {token}'
         }
    url2 = "https://pluginng.com/api/purchase/data"
    payload2 = {
      "plan_id": plan.pluginng_plan_id,
      "subcategory_id": 58,
      "phonenumber": phone,
      "ported": "yes",
      "custom_reference": request_id
    }

 
    try:
        responses = requests.post(url2, headers=headers, json=payload2)
        response = responses.json()
        if 'success' in response:
            stat = response['success']
            if stat == True:
                status = 'successful'
                api = response['message']
            elif stat == False and response['message'] == "Transaction pending":
                status = 'processing'
                api = response['message']
            else:
                status = 'failed'
                api = response['message']
        else:
            status = 'failed'
            api = "Transaction Failed"
    except:
        status = 'failed'
        api = "Transaction Failed"

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




