# -*- 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

from xivo_dao.alchemy.agentfeatures import AgentFeatures
from xivo_dao.alchemy.agentgroup import AgentGroup
from xivo_dao.alchemy.queuemember import QueueMember
from xivo_dao.alchemy.queuefeatures import QueueFeatures
from xivo_dao.helpers.db_manager import daosession
from xivo_dao.helpers.db_manager import Session
from xivo_dao.resources.agent.search import agent_search
from xivo_dao.resources.utils.search import SearchResult


@daosession
def exists(session, agent_id):
    query = (session.query(AgentFeatures)
             .filter(AgentFeatures.id == agent_id)
             )

    return query.count() > 0

def search(**parameters):
    rows, total = agent_search.search(Session, parameters)
    return SearchResult(total, rows)

def get(agent_id):
    query = Session.query(AgentFeatures).filter_by(id=agent_id)
    return query.first()

def create(agent):
    Session.add(agent)
    Session.flush()
    return agent

def edit(agent):
    Session.add(agent)
    Session.flush()
    return agent

def delete(agent):
    Session.delete(agent)
    Session.flush()

def to_membership_dict(row):
    return {
        'agent_id': row[0],
        'queue_id': row[1],
        'penalty': row[2]
    }


def get_membership(agent_id):
    query = (Session.query(QueueMember.userid.label('agent_id'),
                           QueueFeatures.id.label("queue_id"),
                           QueueMember.penalty)
             .filter(QueueFeatures.name == QueueMember.queue_name)
             .filter(QueueMember.usertype == 'agent')
             .filter(QueueMember.userid == agent_id))

    rows = query.all()

    return [to_membership_dict(item) for item in rows]

def get_group_by_id(group_id):
    query = (Session.query(AgentGroup)
             .filter(AgentGroup.id == group_id))

    return query.first()
