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

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

from sqlalchemy.sql import select

from xivo_dao.alchemy.cel import CEL as CELSchema
from xivo_dao.helpers.db_manager import daosession


@daosession
def find_last_unprocessed(session, limit):
    linked_ids = (select(CELSchema.linkedid)
                  .filter(CELSchema.call_log_id == None)
                  .order_by(CELSchema.eventtime.desc())
                  .limit(limit))
    cel_rows = (session
                .query(CELSchema)
                .filter(CELSchema.linkedid.in_(linked_ids))
                .order_by(CELSchema.eventtime.desc())
                .all())
    cel_rows.reverse()
    return cel_rows


@daosession
def find_from_linked_id(session, linked_id):
    cel_rows = (session
                .query(CELSchema)
                .filter(CELSchema.linkedid == linked_id)
                .order_by(CELSchema.eventtime.asc())
                .all())
    return cel_rows
