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

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

import logging
import os

from hamcrest import assert_that, contains_exactly
from sqlalchemy.engine import create_engine
from sqlalchemy.orm import sessionmaker
from xivo_dao.alchemy.meetingroom import MeetingRoom

from xivo_dird.dao import database
from .base_dird_integration_test import BaseDirdIntegrationTest

logger = logging.getLogger(__name__)

db_uri_default = 'postgresql://asterisk:proformatique@localhost:15432'

Session = sessionmaker(bind=create_engine(os.getenv('DB_URI', db_uri_default)))

rooms = (
    {
        "display_name": "Bat",
        "room_type": "static",
        "number": 1001,
        "id": 1
    },
    {
        "display_name": "Bobby Bat",
        "room_type": "static",
        "number": 1002,
        "id": 2
    },
)

persons = (
    {'firstname': 'Violet', 'lastname': 'Caterpillar', 'name': 'Violet Caterpillar'},
    {'firstname': 'Polecat', 'lastname': 'Striped', 'name': 'Polecat Striped'},
    {'firstname': 'Nice', 'lastname': 'Cute', 'company': 'Cat', 'name': 'Nice Cute'},
    {'firstname': 'Cat', 'lastname': 'White', 'name': 'Cat White'},
    {'firstname': 'Black', 'lastname': 'Cat', 'name': 'Black Cat'},
)


def insert_meeting_rooms(*rooms):
    session = Session()
    for room in rooms:
        room = MeetingRoom(**room)
        session.add(room)
        session.flush()
    session.commit()


def setup():
    BaseTest.setUpClass()
    database.Base.metadata.bind = create_engine(os.getenv('DB_URI', db_uri_default))
    database.Base.metadata.reflect()
    database.Base.metadata.drop_all()
    database.Base.metadata.create_all()
    insert_meeting_rooms(*rooms)

    for person in persons:
        BaseTest.post_personal(person)


def teardown():
    BaseTest.tearDownClass()


class BaseTest(BaseDirdIntegrationTest):
    asset = 'search_sort'


class TestSearchSorting(BaseTest):
    uuid = "6fa459ea-ee8a-3ca4-894e-db77e160355e"

    def test_that_the_lookup_returns_properly_sorted(self):
        expected_results = [
            ['Black Cat', None, None, False, 'Black', 'Cat'],
            ['Cat White', None, None, False, 'Cat', 'White'],
            ['Violet Caterpillar', None, None, False, 'Violet', 'Caterpillar'],
            ['Polecat Striped', None, None, False, 'Polecat', 'Striped'],
            ['Bat', 'Bat', '1001', False, None, None]
        ]
        result = list([_['column_values'] for _ in self.lookup('cat', 'default')['results']])
        assert_that(result, contains_exactly(*expected_results))
