# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-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 sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session

from xivo_dird import BaseSourcePlugin
from xivo_dird import make_result_class
from xivo_dird import database


logger = logging.getLogger(__name__)

session = scoped_session(sessionmaker())


class MeetingroomBackend(BaseSourcePlugin):

    STATIC = database.MeetingroomSearchEngine.STATIC
    PERSONAL = database.MeetingroomSearchEngine.PERSONAL

    def load(self, config, search_engine=None):
        logger.debug(
            'Loading meeting room source. %s',
            'Search engine was supplied.' if search_engine else 'Search engine will be created.'
        )

        unique_column = 'id'
        source_name = config['config']['name']
        format_columns = config['config'].get(self.FORMAT_COLUMNS, {})

        self.room_result = make_result_class(
            source_name,
            unique_column,
            format_columns,
        )
        if search_engine:
            self._search_engine = search_engine
        else:
            session.configure(bind=create_engine(config['config']['db_uri']))
            self._search_engine = search_engine or database.MeetingroomSearchEngine(
                session,
                config['config'].get(self.SEARCHED_COLUMNS),
                config['config'].get(self.FIRST_MATCHED_COLUMNS)
            )

        self.xivo_uuid = os.getenv('XIVO_UUID')

    def search(self, term, args=None):
        logger.debug('Searching meeting room with %s, %s', term, args)
        user_uuid = args.get('xivo_user_uuid')
        matching_rooms = self._search_engine.find(term=term, user_uuid=user_uuid)
        return self.format_rooms(matching_rooms, user_uuid=user_uuid)

    def first_match(self, term, args=None):
        logger.debug('First matching meeting room with %s, %s', term, args)
        user_uuid = args.get('xivo_user_uuid')
        rooms = list(self._search_engine.find_first(term=term, user_uuid=user_uuid, limit=1))
        return self.format_room(rooms[0], user_uuid=user_uuid) if rooms else dict()

    def list(self, source_entry_ids, args=None):
        logger.debug('Listing meeting rooms - %s, %s', source_entry_ids, args)
        user_uuid = args.get('token_infos', {}).get('xivo_user_uuid')
        matching_rooms = self._search_engine.find(user_uuid=user_uuid, ids=source_entry_ids)
        return self.format_rooms(matching_rooms, user_uuid=user_uuid)

    def format_room(self, room, user_uuid=None):
        personal = room.pop('room_type')
        room = self.room_result(room, user_uuid=user_uuid, xivo_id=self.xivo_uuid)
        room.is_personal = (personal == self.PERSONAL)
        return room

    def format_rooms(self, rooms, user_uuid=None):
        return [self.format_room(_, user_uuid=user_uuid) for _ in rooms]
