import numbers
from operator import sub
import subprocess
from pathlib import Path
import re
from unittest import result
import requests

mbapi_path = Path('D:\Proyectos\scrapper-portabilidad\magnus-api')
succesful = re.compile(r'^\[20\d\]')


class MagnusCommandError(Exception):
    pass


def _create_user(phone_number: str, password: str, name: str, surname: str):
    """Genera una cuenta de usuario en MagnusBilling

    """

    result = subprocess.check_output(
        ['php', Path(mbapi_path, 'create_user.php'),
         phone_number, password, name, surname]
    )
    if not re.match(succesful, result.decode(encoding='utf-8')):
        raise MagnusCommandError(result.decode(encoding='utf-8'))


def _create_sip(phone_number: str, password: str, pbx: str = None):
    command = ['php', Path(mbapi_path, 'create_sip.php'),
               phone_number, password]
    if pbx:
        command.append(pbx)

    result = subprocess.check_output(command)

    if not re.match(succesful, result.decode(encoding='utf-8')):
        raise MagnusCommandError(result.decode(encoding='utf-8'))


def _create_did(phone_number: str):
    """Genera un DID

    """

    for did in (phone_number, f'34{phone_number}'):
        result = subprocess.check_output(
            ['php', Path(mbapi_path, 'create_did.php'), did]
        )

        result = subprocess.check_output(
            ['php', Path(mbapi_path, 'assign_did.php'), phone_number, did]
        )

        if not re.match(succesful, result.decode('utf-8')):
            raise MagnusCommandError(result.decode('utf-8'))


def create_user(phone_number: str, name: str, surname: str, password: str = None, pbx: str = None, balance: float = 0.0):
    """Crea a un nuevo usuario en MagnusBilling

    """

    password = password if password else ''.join(
        (name.split(' ')[0].lower(), phone_number[4:6]))
    _create_user(phone_number, password, name, surname)
    _create_sip(phone_number, password, pbx)
    _create_did(phone_number)

    response = {'number': phone_number}

    if pbx:
        response['outgoing'] = f'type = friend\nusername = {phone_number}\nhost = 192.168.2.84\nnat = force_rport, comedia\nqualify = yes\ninsecure = invite, port'
        response['incoming'] = 'type = friend\nhost = 192.168.2.84\nnat = force_rport, comedia\nqualify = yes\ninsecure = invite, port'
    else:
        response['password'] = phone_number

    return response


def add_trunk_account(pbx: str, username: str, password: str):
    """Añade la troncal a una Centralita

    """
    base = pbx if re.match(r'^https:/.*$', pbx) else f'https://{pbx}'
    with requests.Session() as s:
        r = s.post(
            url=base,
            verify=False,
            data={
                'input_user': 'admin',
                'input_pass': 'Mur5cKUBatdw',
                'submit_login': ''
            }
        )

        r = s.get(
            url=f'{base}/config.php?display=trunks&tech=SIP'
        )

        print(r.content)


account = {
    'number': '956385412',
    'name': 'AkunaDecor',
    'surname': 'Interiorismo S.L.',
    'pbx': '192.168.2.54'
}


user = create_user(phone_number = account['number'], name = account['name'], surname = account['surname'], pbx= account['pbx'])

print(f'url: {account["pbx"]}')
print('--------')
print(user['number'])
print('--------')
print(user['outgoing'])
print('--------')
print(user['incoming'])
print('--------')
