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

#    Copyright 2018 Fabien Bourgeois <fabien@yaltik.com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

""" Odoo Radicale Authentication Plugin """

from configparser import Error
from odoorpc import ODOO
from odoorpc.error import RPCError
from radicale.auth import BaseAuth


class Auth(BaseAuth):
    """ BaseAuth implementation for Odoo Radicale Authentication """

    odoo = False

    def __init__(self, configuration, logger):
        super(Auth, self).__init__(configuration, logger)
        host = self.configuration.get('auth', 'odoo_host', fallback='127.0.0.1')
        port = self.configuration.get('auth', 'odoo_port', fallback=8069)
        try:
            self.__class__.odoo = ODOO(host, port=port)
        except RPCError as rpcerr:
            self.logger.error(rpcerr)
            raise RuntimeError(rpcerr)

    def is_authenticated(self, user, password):
        """ Is authenticated main function """
        if not self.configuration.has_option('auth', 'odoo_database'):
            raise RuntimeError('Database is needed for Odoo Authentication')
        database = self.configuration.get('auth', 'odoo_database')
        if not user or not password:
            return False
        try:
            self.__class__.odoo.login(database, user, password)
            self.logger.info('Login successfull for {} on database {}'.format(user, database))
            return True
        except RPCError as rpcerr:
            self.logger.error('Login problem for {} on database {}'.format(user, database))
            self.logger.error(rpcerr)
        return False