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

# Copyright (C) 2020 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 sqlite3 import IntegrityError

from xivo_dao.alchemy.labels import Labels
from xivo_dao.helpers.db_manager import Session
from xivo_dao.helpers.db_manager import daosession
from xivo_dao.resources.labels.search import label_search
from xivo_dao.resources.utils.search import SearchResult


@daosession
def exists(session, label_id):
    query = (session.query(Labels)
             .filter(Labels.id == label_id)
             )

    return query.count() > 0


def get(label_id):
    query = Session.query(Labels).filter_by(id=label_id)
    return query.first()


def get_by_display_name(label_display_name):
    query = Session.query(Labels).filter(Labels.display_name == label_display_name)
    return query.first()


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


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


def delete(label):
    label = get(label.id)
    _disassociate(label)
    Session.delete(label)
    Session.flush()


def _disassociate(label):
    label.user_features = []
    Session.flush()


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