# -*- 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 os.path
import unittest
import uuid

import yaml
from hamcrest import assert_that, equal_to

from xivo_auth import static_token_manager


class TestStaticTokenManager(unittest.TestCase):

    def setUp(self):
        self.conf_file_path = '/tmp/unittest-xivo-auth-conf.yaml'
        self.manager = static_token_manager.StaticTokenManager(self.conf_file_path)

    def _remove_conf_file(self):
        try:
            os.remove(self.conf_file_path)
        except:
            pass

    def _create_config_file(self):
        if (not os.path.isfile(self.conf_file_path)):
            with open(self.conf_file_path, 'w') as f:
                f.write('dummy_config:')

    def _is_uuid(self, data):
        try:
            uuid.UUID(data)
            return True
        except:
            return False

    def _get_config(self):
        try:
            with open(self.conf_file_path, 'r') as outfile:
                return yaml.unsafe_load(outfile)
        except IOError:
            return None

    def test_generate_new(self):
        self._remove_conf_file()
        self.manager.write_config(self.manager.get_new_config())

        config = self._get_config()
        assert_that(isinstance(config['static_service_tokens']['xc']['token'], uuid.UUID), equal_to(True))
        self._remove_conf_file()

    def test_do_not_overwrite(self):
        self._create_config_file()
        with self.assertRaises(static_token_manager.ConfigFileExists):
            self.manager.write_config(self.manager.get_new_config())
