from requests import Session
from enum import Enum

from requests.models import HTTPError

magnus = "http://192.168.2.56/mbilling/index.php"
login = {
    'user' : 'root',
    'password' : 'NgtAtONgeRaFtsbu',
}

class Tarifa(Enum):
    ESTANDAR = 1
    EMPRESA = 2
    PTV = 4

def generate_rows(tarifa : Tarifa, telefono : str, id_cliente : int, nombre : str, apellido : str, email : str) -> str:
    """Genera cadena Row para creación de Cliente
    
    """
    row = f'id" : 0,"id_group" : 3,"id_plan" : {tarifa.value},"id_user" : 0,"username" : {telefono},"password" : {id_cliente},"active" : 1,"credit" : 0,'
    row = ''.join((row,f'"enableexpire" : 0,"expiredays" : 0,"credit_notification" : -1,"restriction" : 0,"callingcard_ping" : {id_cliente},"callshop" : 0,'))
    row = ''.join((row,f'"plan_day" : 0,"active_paypal" : 0,"boleto" : 0,"lastname" : {apellido.capitalize()},"firstname" : {nombre.capitalize()},"redial" : "",'))
    row = ''.join((row,f'"tag" : "","company_name" : {nombre.capitalize()},"commercial_name" : {" ".join((nombre.capitalize(), apellido.capitalize()))},"address" : "",'))
    row = ''.join((row,f'"city" : "","state" : " ","country" : "1","loginkey" : "","zipcode" : "","phone" : "","mobile" : "","email" : {email},"doc" : "","vat" : "",'))
    row = ''.join((row,f'"language" : "es","company_website" : "","prefix_local" : "","boleto_day" : 0,"firstusedate":null,"expirationdate":null,"lastuse":null,'))
    row = ''.join((row,f'"description":"","creationdate":null,"id_group_agent":0,"calllimit":-1,"mix_monitor_format":"gsm","disk_space":-1,"sipaccountlimit":-1,'))
    row = ''.join((row,f'"cpslimit":-1,"state_number":"","neighborhood":"","calllimit_error":"503","transfer_international":0,"transfer_international_profit":null,'))
    row = ''.join((row,f'"transfer_flexiload":0,"transfer_flexiload_profit":null,"transfer_bkash":0,"transfer_bkash_profit":null,"transfer_dbbl_rocket":0,'))
    row = ''.join((row,f'"transfer_dbbl_rocket_profit":null,"transfer_bdservice_rate":null,"transfer_show_selling_price":null'))
    return '{"id":0,"id_group":3,"id_plan":1,"id_user":0,"id_offer":0,"username":"test","password":"2uQqJH8F","active":1,"credit":0,"enableexpire":0,"expiredays":0,"status":0,"typepaid":0,"creditlimit":0,"credit_notification":-1,"restriction":0,"callingcard_pin":891457,"callshop":0,"plan_day":0,"active_paypal":0,"boleto":0,"lastname":"TEST","firstname":"TEST","redial":"","tag":"","company_name":"","commercial_name":"","address":"","city":"","state":"","country":"1","loginkey":"","zipcode":"","phone":"","mobile":"","email":"","doc":"","vat":"","language":"es","company_website":"","prefix_local":"","boleto_day":0,"firstusedate":null,"expirationdate":null,"lastuse":null,"description":"","creationdate":null,"id_group_agent":0,"calllimit":-1,"mix_monitor_format":"gsm","disk_space":-1,"sipaccountlimit":-1,"cpslimit":-1,"state_number":"","neighborhood":"","calllimit_error":"503","transfer_international":0,"transfer_international_profit":null,"transfer_flexiload":0,"transfer_flexiload_profit":null,"transfer_bkash":0,"transfer_bkash_profit":null,"transfer_dbbl_rocket":0,"transfer_dbbl_rocket_profit":null,"transfer_bdservice_rate":null,"transfer_show_selling_price":null}'

def set_headers(cnx : Session):
    cnx.headers['Accept-Encoding'] = 'gzip, deflate'
    cnx.headers['Connection'] = 'keep-alive'
    cnx.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
    cnx.headers['Referer'] = magnus.replace('index.php', '')
    cnx.headers['Origin'] = magnus.replace('/mbilling/index.php', '')

def create_account(nombre : str, telefono : str, id_cliente : int, email : str = "", apellido : str = '', tarifa : Tarifa = Tarifa.ESTANDAR):

    with Session() as cnx:
        set_headers(cnx)
        cnx.get(magnus)
        cnx.post(f'{magnus}/authentication/login', data=login).raise_for_status()

        response = cnx.post(f'{magnus}/user/save',  data={
            'rows' : generate_rows(tarifa, telefono, id_cliente, nombre, apellido, email)
        })

        try:
            response.raise_for_status()
        except HTTPError as e:
            print(response.request.headers)
        finally:
            with open('result.html', 'wb') as f:
                f.write(response.content)


create_account(tarifa=Tarifa.ESTANDAR,nombre="Cliente",telefono="856856856",id_cliente=256452,email="pruebas@pruebas.es")

