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

# Copyright (C) 2018 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 re
import unittest

from mock import Mock, patch
from xivo_dao.helpers.exception import ResourceError
from xivo_dao.resources.user_cti_profile.model import UserCtiProfile

from xivo_confd.plugins.user_cti_profile.validator import _validate_user_has_login_passwd


class TestValidator(unittest.TestCase):
    missing_username_password_regex = re.compile(r"User must have a username and password to enable a CtiProfile")

    @patch('xivo_dao.resources.user.dao.get')
    def test_validate_user_with_existing_cti_profile(self, mock_dao):
        user = Mock()
        user.username = 'username'
        user.password = 'password'
        mock_dao.return_value = user
        cti_profile = UserCtiProfile(user_id=1,
                                     cti_profile_id=1,
                                     enabled='enabled',
                                     username='newusername',
                                     password='newpassword')
        _validate_user_has_login_passwd(cti_profile)

    @patch('xivo_dao.resources.user.dao.get')
    def test_validate_user_with_no_cti_profile(self, mock_dao):
        user = Mock()
        user.username = None
        user.password = None
        mock_dao.return_value = user
        cti_profile = UserCtiProfile(user_id=1,
                                     cti_profile_id=1,
                                     enabled='enabled')
        self.assertRaises(ResourceError, _validate_user_has_login_passwd, cti_profile)

    @patch('xivo_dao.resources.user.dao.get')
    def test_validate_user_with_cti_username_and_password_on_import(self, mock_dao):
        user = Mock()
        user.username = None
        user.password = None
        mock_dao.return_value = user
        cti_profile = UserCtiProfile(user_id=1,
                                     cti_profile_id=1,
                                     enabled='enabled',
                                     username='username',
                                     password='password')
        _validate_user_has_login_passwd(cti_profile)
