# -*- coding: utf-8 -*-

# Copyright (C) 2015 Avencall
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>


import logging
import os
import subprocess

from xivo_sysconf.request_handlers.command import Command
from xivo.config_helper import get_sip_driver

logger = logging.getLogger(__name__)


class AsteriskCommands(object):
    _SIP_RELOAD_COMMANDS = {
        'SIP': 'sip reload',
        'PJSIP': 'module reload res_pjsip.so'
    }

    _COMMANDS = [
        'core reload',
        'core restart now',
        'dialplan reload',
        'moh reload',
        'iax2 reload',
        'module reload app_queue.so',
        'module reload app_meetme.so',
        'module reload features',
        'module reload res_parking.so',
        'voicemail reload',
        'module reload chan_sccp.so',
        'module reload res_rtp_asterisk.so',
    ]
    _ARG_COMMANDS = [
        'sccp reset'
    ]


class AsteriskCommandFactory(AsteriskCommands):

    def __init__(self, asterisk_command_executor):
        self._executor = asterisk_command_executor
        self.sip_driver = get_sip_driver()
        logger.debug(f"Sip driver: {self.sip_driver}")

    def new_command(self, value):
        if value in self._SIP_RELOAD_COMMANDS.values():
            value = self._SIP_RELOAD_COMMANDS[self.sip_driver]
        else:
            self._check_validity(value)
        return Command(value, self._executor, value)

    def _check_validity(self, value):
        if value in self._COMMANDS:
            return
        for arg_cmd in self._ARG_COMMANDS:
            if value.startswith(arg_cmd):
                return
        raise ValueError(f'Unauthorized command "{value}"!')


class AsteriskCommandExecutor(AsteriskCommands):

    def __init__(self):
        self._null = open(os.devnull)

    def _generate_atomic_way_pjsip_conf(self):
        subprocess.call('/usr/bin/xivo-confgen asterisk/pjsip.conf > /etc/asterisk/pjsip.conf.chan_pjsip', shell=True)
        subprocess.call('chown asterisk:www-data /etc/asterisk/pjsip.conf.chan_pjsip', shell=True)
        subprocess.call('chmod 660 /etc/asterisk/pjsip.conf.chan_pjsip', shell=True)

    def execute(self, data):
        if data == self._SIP_RELOAD_COMMANDS['PJSIP']:
            self._generate_atomic_way_pjsip_conf()

        exit_code = subprocess.call(['asterisk', '-rx', data], stdout=self._null, close_fds=True)
        if exit_code:
            logger.error('asterisk returned non-zero status code %s', exit_code)
