# -*- 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, equal_to
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, VALID_UUID

logger = logging.getLogger(__name__)

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

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

values = [
    {
        "display_name": "room",
        "room_type": "static",
        "number": 1001,
        "id": 1
    },
    {
        "display_name": "my meeting",
        "room_type": "static",
        "number": 1002,
        "id": 2
    },
]


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(*values)


def teardown():
    BaseTest.tearDownClass()


class BaseTest(BaseDirdIntegrationTest):
    asset = 'xivo_meetingroom'


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

    def test_that_the_lookup_returns_the_expected_result_meetingroom_direct(self):
        result = self.lookup('room', 'default')

        assert_that(
            result['results'][0]['column_values'],
            contains_exactly('room', None, '1001', False)
        )
        assert_that(
            result['results'][0]['relations'],
            equal_to(
                {'xivo_id': None,
                 'agent_id': None,
                 'endpoint_id': None,
                 'user_id': None,
                 'user_uuid': 'uuid',
                 'source_entry_id': '1'}
            )
        )

    def test_no_result(self):
        result = self.lookup('wat??', 'default')

        assert_that(result['results'], contains_exactly())

    def test_that_the_reverse_lookup_returns_the_expected_result(self):
        result = self.reverse('1001', 'default', VALID_UUID)
        logger.warning(result)

        assert_that(result['fields']['display_name'], equal_to('room'))
