# -*- coding: utf-8 -*-
import os
import tempfile
import unittest
import urllib.request

from hamcrest import assert_that, equal_to, is_

from provd.xivo_version import get_xivo_version
from provd.xivo_version import XivoVersionHandler
from provd.xivo_version import plugin_download_handlers


class TestGetXivoVersion(unittest.TestCase):

    def _write(self, content):
        fd, path = tempfile.mkstemp()
        self.addCleanup(os.remove, path)
        with os.fdopen(fd, 'w') as f:
            f.write(content)
        return path

    def test_returns_stripped_content(self):
        path = self._write('2026.09.00\n')
        assert_that(get_xivo_version(path), equal_to('2026.09.00'))

    def test_missing_file_returns_none(self):
        assert_that(get_xivo_version('/nonexistent/XIVO-VERSION'), is_(None))

    def test_blank_file_returns_none(self):
        path = self._write('   \n')
        assert_that(get_xivo_version(path), is_(None))


class TestXivoVersionHandler(unittest.TestCase):

    def test_adds_header_to_http_request(self):
        handler = XivoVersionHandler('2026.09.00')
        req = urllib.request.Request('http://provd.example/plugins/2/stable/plugins.db')
        out = handler.http_request(req)
        assert_that(out.get_header('X-xivo-version'), equal_to('2026.09.00'))

    def test_adds_header_to_https_request(self):
        handler = XivoVersionHandler('2026.09.00')
        req = urllib.request.Request('https://provd.example/plugins/2/stable/plugins.db')
        out = handler.https_request(req)
        assert_that(out.get_header('X-xivo-version'), equal_to('2026.09.00'))


class TestPluginDownloadHandlers(unittest.TestCase):

    def _write(self, content):
        fd, path = tempfile.mkstemp()
        self.addCleanup(os.remove, path)
        with os.fdopen(fd, 'w') as f:
            f.write(content)
        return path

    def test_includes_version_handler_when_version_present(self):
        path = self._write('2026.09.00\n')
        handlers = plugin_download_handlers(None, xivo_version_file=path)
        version_handlers = [h for h in handlers if isinstance(h, XivoVersionHandler)]
        assert_that(len(version_handlers), equal_to(1))
        assert_that(version_handlers[0]._version, equal_to('2026.09.00'))

    def test_no_version_handler_when_version_absent(self):
        handlers = plugin_download_handlers(None, xivo_version_file='/nonexistent/XIVO-VERSION')
        version_handlers = [h for h in handlers if isinstance(h, XivoVersionHandler)]
        assert_that(version_handlers, equal_to([]))
