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

# Copyright (C) 2013-2016 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 xivo_confd.plugins.user.validator import build_validator, build_validator_forward
from xivo_confd.plugins.user.notifier import build_notifier, build_notifier_service, build_notifier_forward
from xivo_confd.plugins.device.builder import build_device_updater

from xivo_confd.helpers.resource import CRUDService
from xivo_confd.helpers.validator import ValidationGroup

from xivo_dao.alchemy.agentfeatures import AgentFeatures
from xivo_dao.helpers import errors
from xivo_dao.helpers.exception import InputError
from xivo_dao.helpers.db_manager import Session
from xivo_dao.resources.user import dao as user_dao
from xivo_dao.resources.func_key.persistor import DestinationPersistor
from xivo_dao import user_dao as user_dao_api
from xivo_dao import agent_dao as agent_dao_api

class UserBaseService(CRUDService):

    def get(self, user_id):
        return self.dao.get_by_id_uuid(user_id)


class UserService(UserBaseService):

    def __init__(self, dao, validator, notifier, device_updater):
        super(UserService, self).__init__(dao, validator, notifier)
        self.device_updater = device_updater

    def get_with_agent(self, user_id):
        return user_dao_api.get_user_with_agent_number(user_id)

    def create_with_agent(self, model, agent_number, agent_group_id):
        self.validator.validate_create(model)
        agent = None

        if agent_number is not None and model.agentid is not None:
            raise InputError('Fields agent_number and agentid can\'t both be set')
        
        if agent_number is not None:
            numgroup = agent_group_id if agent_group_id is not None else 1
            agent = AgentFeatures(
                firstname=model.firstname,
                lastname=model.lastname,
                number=agent_number,
                numgroup=numgroup,
                passwd='',
                context='default',
                language='',
                description='')
            Session.add(agent)
            Session.flush()
            DestinationPersistor(Session).create_agent_destination(agent)
            model.agentid = agent.id
        created_resource = self.dao.create(model)
        self.notifier.created(created_resource)
        if agent is not None:
            self.notifier.created_agent(agent, created_resource)
        return created_resource

    def edit(self, user, reload_device=True):
        with Session.no_autoflush:
            self.validator.validate_edit(user)
        self.dao.edit(user)
        self.notifier.edited(user)
        if reload_device:
            self.device_updater.update_for_user(user)

    def edit_with_agent(self, user, agent_number, agent_group_id):
        if agent_number is None and user.agentid is not None:
            agent = agent_dao_api.get(user.agentid)
            self.notifier.edited_agent(agent)
            user.agentid = None


        if agent_number is not None:
            numgroup = agent_group_id if agent_group_id is not None else 1
            if user.agentid is None or user.agentid == 0:
                agent = AgentFeatures(
                    firstname=user.firstname,
                    lastname=user.lastname,
                    number=agent_number,
                    numgroup=numgroup,
                    passwd='',
                    context='default',
                    language='',
                    description='')
                Session.add(agent)
                Session.flush()
                DestinationPersistor(Session).create_agent_destination(agent)
                user.agentid = agent.id
                self.notifier.created_agent(agent, user)
            else:
                (_, old_agent_number, old_agent_group_id) = self.get_with_agent(user.id)
                if(old_agent_number != agent_number):
                    raise errors.invalid_query_parameter('agent_number', agent_number)
                if(agent_group_id is not None and old_agent_group_id != agent_group_id):
                    Session.query(AgentFeatures).filter_by(id=user.agentid).update({"numgroup": agent_group_id})
                    agent = agent_dao_api.get(user.agentid)
                    self.notifier.edited_agent(agent)
        self.edit(user)

    def edit_agent_group(self, user, agent_group_id):
        (_, _, old_agent_group_id) = self.get_with_agent(user.id)
        if agent_group_id is not None and old_agent_group_id != agent_group_id:
            Session.query(AgentFeatures).filter_by(id=user.agentid).update({"numgroup": agent_group_id})
            
        self.edit(user)

    def legacy_search(self, term):
        return self.dao.legacy_search(term)


def build_service(provd_client):
    updater = build_device_updater(provd_client)
    return UserService(user_dao,
                       build_validator(),
                       build_notifier(),
                       updater)


class UserCallServiceService(UserBaseService):

    def edit(self, user, schema):
        self.validator.validate_edit(user)
        self.dao.edit(user)
        self.notifier.edited(user, schema)


def build_service_callservice():
    return UserCallServiceService(user_dao,
                                  ValidationGroup(),
                                  build_notifier_service())


class UserForwardService(UserBaseService):

    def edit(self, user, schema):
        self.validator.validate_edit(user)
        self.dao.edit(user)
        self.notifier.edited(user, schema)


def build_service_forward():
    return UserForwardService(user_dao,
                              build_validator_forward(),
                              build_notifier_forward())
