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

# Copyright (C) 2019 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/>

from flask import url_for
from flask_restful import reqparse, fields, marshal
from xivo_dao.alchemy.agentfeatures import AgentFeatures
from xivo_dao.helpers import errors
from xivo_dao.helpers.db_manager import Session
from xivo_dao.resources.func_key.persistor import DestinationPersistor

from xivo_confd.authentication.confd_auth import required_acl
from xivo_confd.helpers.restful import ListResource, ItemResource, Strict, ConfdResource

agent_fields = {
    'id': fields.Integer,
    'firstname': fields.String,
    'lastname': fields.String,
    'number': fields.String,
    'numgroup': fields.Integer,
    'context': fields.String,
    'language': fields.String,
    'description': fields.String,
    'passwd': fields.String
}

agent_queue_fields = {
    'agent_id': fields.Integer,
    'queue_id': fields.Integer,
    'penalty': fields.Integer
}

parser = reqparse.RequestParser()
parser.add_argument('firstname', type=Strict(str), store_missing=False, nullable=False)
parser.add_argument('lastname', type=Strict(str), store_missing=False)
parser.add_argument('number', type=Strict(str), store_missing=False)
parser.add_argument('numgroup', type=int, store_missing=False)
parser.add_argument('context', type=Strict(str), store_missing=False)
parser.add_argument('language', type=Strict(str), store_missing=False)
parser.add_argument('description', type=Strict(str), store_missing=False)
parser.add_argument('passwd', type=Strict(str), store_missing=False)


class AgentList(ListResource):
    model = AgentFeatures
    fields = agent_fields
    parser = parser

    def build_headers(self, agent):
        return {'Location': url_for('agents', id=agent.id, _external=True)}

    @required_acl('confd.agents.create')
    def post(self):
        form = self.parser.parse_args()
        form.setdefault('numgroup', 1)
        form.setdefault('passwd', '')
        form.setdefault('context', 'default')
        form.setdefault('language', 'fr_FR')
        form.setdefault('description', '')
        model = self.model(**form)
        model.autologoff = 0
        agent = self.service.create(model)
        DestinationPersistor(Session).create_agent_destination(agent)
        marshalled = marshal(agent, self.fields)
        return marshalled, 201, self.build_headers(agent)

    @required_acl('confd.agents.read')
    def get(self):
        params = self.search_params()
        result = self.service.search(params)
        return {'total': result.total,
                'items': [marshal(item, self.fields) for item in result.items]}


class AgentItem(ItemResource):
    fields = agent_fields
    parser = parser
    persistor = DestinationPersistor(Session)

    @required_acl('confd.agents.{id}.read')
    def get(self, id):
        model = self.service.get(id)
        if model is None:
            raise errors.not_found('Agent', id=id)
        marshalled = marshal(model, self.fields)
        return marshalled

    @required_acl('confd.agents.{id}.update')
    def put(self, id):
        model = self.service.get(id)
        if model is None:
            raise errors.not_found('Agent', id=id)
        form = self.parser.parse_args()
        for name, value in form.items():
            setattr(model, name, value)

        self.service.edit(model)
        return '', 204

    @required_acl('confd.agents.{id}.delete')
    def delete(self, id):
        agent = self.service.get(id)
        if agent is None:
            raise errors.not_found('Agent', id=id)
        self.persistor.delete_agent_destination(agent)
        return super(AgentItem, self).delete(id)


class AgentQueueList(ConfdResource):

    def __init__(self, service):
        self.service = service
        self.fields = agent_queue_fields

    @required_acl('confd.agents.{id}.read')
    def get(self, id):
        memberships = self.service.get_agent_membership(id)
        return [marshal(item, self.fields) for item in memberships]
