#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ~ Author: Pavel Ivanov

from flask import Blueprint
from flask_httpauth import HTTPTokenAuth

from asterisk.ami import AMIClient, AMIClientAdapter
from flask_server import app, jsonrpc

from models import asterisk
from models.session import Session

import jinja2
import os


mod_auth = Blueprint('auth', __name__)
auth = HTTPTokenAuth(scheme='WWWToken')
jsonrpc.register_blueprint(mod_auth)


@auth.verify_token
def verify_token(token):
    """Верификация токена авторизации

    """
    return Session.get_active(token) is not None


def generate_extensions_conf():
    """ Генерация файла extensions.conf
    
    :return: None
    """
    path, filename = os.path.split("./static/asterisk/extensions.conf.tmpl")

    conf_file = jinja2.Environment(loader=jinja2.FileSystemLoader(path)).get_template(filename).render({
        "contexts": asterisk.AsteriskContext.query.all(),
    })

    with open(app.config.get("ASTERISK_PATH_EXTENSIONS_CONF"), "w") as fp:
        fp.write(conf_file)
        fp.close()


def send_command(command: str):
    """ Отправка команды в Asterisk
    
    :param command: str
    :return: None
    """
    client = AMIClient(address=app.config.get("ASTERISK_AMI_SERVER"), port=app.config.get("ASTERISK_AMI_PORT"))
    client.login(username=app.config.get("ASTERISK_AMI_MANAGER"), secret=app.config.get("ASTERISK_AMI_PASSWORD"))

    adapter = AMIClientAdapter(client)
    adapter.Command(Command=command)

    client.logoff()


@jsonrpc.method("Asterisk.generate_extentions_conf()")
@auth.login_required
def asterisk_generate_extentions_conf():
    """ Генерация extensions.conf

    :return: None
    """
    generate_extensions_conf()


@jsonrpc.method("Asterisk.ami_sip_reload()")
@auth.login_required
def asterisk_ami_sip_reload():
    """ Перезагрузка Asterisk SIP
    
    :return: None
    """
    send_command("sip reload")


@jsonrpc.method("Asterisk.ami_dialplan_reload()")
@auth.login_required
def asterisk_dialplan_reload():
    """ Перезагрузка Asterisk Dialplan

    :return: None
    """
    send_command("dialplan reload")

