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

# Copyright (C) 2013-2018 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 os

from past.builtins import basestring
from xivo_dao import asterisk_conf_dao

from xivo_confgen.generators.util import format_ast_option, \
    format_ast_object_option


class QueuesConf(object):
    DEFAULT_OPTIONS = [
        'allow_wrapup_termination = yes'
    ]

    def __init__(self, mds=False):
        self.mds = mds
        self.systemname = os.getenv('MDS_NAME', 'default')

    def generate(self, output):
        self._print_general_settings(output)
        self._print_settings_and_members(output)

    def _print_general_settings(self, output):
        if self.mds:
            print(';Only group configuration for MDS', file=output)
        print('[general]', file=output)
        for option in self.DEFAULT_OPTIONS:
            print(option, file=output)

        for item in asterisk_conf_dao.find_queue_general_settings():
            print(format_ast_option(item['var_name'], item['var_val']), file=output)

    def _print_settings_and_members(self, output):
        if self.mds:
            queues = asterisk_conf_dao.find_queue_groupfeatures_settings(self.systemname)
        else:
            queues = asterisk_conf_dao.find_queue_queuefeatures_settings()
            queues += asterisk_conf_dao.find_queue_groupfeatures_settings(self.systemname)
            queue_penalty_settings = asterisk_conf_dao.find_queue_penalty_settings()
            penalties = dict((itm['id'], itm['name']) for itm in queue_penalty_settings)

        for q in queues:
            print('\n[%s]' % q['name'], file=output)

            for k, v in q.items():
                if k in ('name', 'category', 'commented') or v is None or \
                        (isinstance(v, basestring) and not v):
                    continue

                if k == 'defaultrule':
                    if int(v) not in penalties:
                        continue
                    v = penalties[int(v)]

                print(format_ast_option(k, v), file=output)

            queuemember_settings = asterisk_conf_dao.find_queue_members_settings(q['name'])
            for m in queuemember_settings:
                member_value = '%s,%d,%s,%s' % (m['interface'], m['penalty'], m['membername'], m['state_interface'])
                print(format_ast_object_option('member', member_value), file=output)
