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

# Copyright (C) 2012-2014 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
from collections import defaultdict

from xivo_agent.ami.actions.common.action import BaseAction

logger = logging.getLogger(__name__)


class QueuesStats(object):
    def __init__(self):
        self.queues = defaultdict(QueueStats)

    def add(self, event):
        self.queues[event.get_value('Queue')].add(event)

    def is_agent_paused(self, name):
        for queue in self.queues.values():
            if queue.is_agent_paused(name):
                return True
        return False


class QueueStats(object):
    event_keys = {
        'QueueParams': [
            'Queue', 'Max', 'Calls', 'Holdtime', 'Completed', 'Abandoned', 'ServiceLevel', 'ServicelevelPerf', 'Weight'
        ],
        'QueueMember': [
            'Queue', 'Name', 'Location', 'Membership', 'Penalty', 'CallsTaken', 'LastCall', 'Status', 'Paused'
        ],
        'QueueEntry': [
            'Queue', 'Position', 'Channel', 'CallerID', 'CallerIDName', 'Wait'
        ]
    }

    def __init__(self):
        self.event_values = {_: list() for _ in self.event_keys.keys()}

    def add(self, event):
        if event.name in self.event_keys.keys():
            self.event_values[event.name].append(event)

    def is_agent_paused(self, name):
        for event in self.event_values['QueueMember']:
            logger.debug('%s pause value: %s', name, event.get_value('Paused'))
            if event.get_value('Name') == name and event.get_value('Paused') == '1':
                return True
        return False


class QueueStatus(BaseAction):

    def __init__(self, queue=None, member=None):
        BaseAction.__init__(self, 'QueueStatus', [('Queue', queue), ('Member', member)])
        self._val = QueuesStats()

    @property
    def val(self):
        self.wait_for_completion()
        return self._val

    def _on_response_received(self, response):
        if not response.is_success():
            self._completed = True

    def _on_event_received(self, event):
        if event.name == 'QueueStatusComplete':
            self._completed = True
        else:
            self._val.add(event)
