# This file is part of Radicale - CalDAV and CardDAV server
# Copyright © 2018-2019 Unrud <unrud@outlook.com>
#
# This library 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 library 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 Radicale.  If not, see <http://www.gnu.org/licenses/>.

"""
Test web plugin.

"""

from radicale import httputils
from radicale.tests import BaseTest


class TestBaseWebRequests(BaseTest):
    """Test web plugin."""

    def test_internal(self) -> None:
        _, headers, _ = self.request("GET", "/.web", check=302)
        assert headers.get("Location") == "/.web/"
        _, answer = self.get("/.web/")
        assert answer
        self.post("/.web", check=405)
        _, answer = self.get("/.web/js/config.js")
        assert "export const PREFER_BROWSER_LOGIN = false;" in answer
        self.configure({"web": {"prefer_browser_login": "True"}})
        _, answer = self.get("/.web/js/config.js")
        assert "export const PREFER_BROWSER_LOGIN = true;" in answer

    def test_none(self) -> None:
        self.configure({"web": {"type": "none"}})
        _, answer = self.get("/.web")
        assert answer
        _, headers, _ = self.request("GET", "/.web/", check=302)
        assert headers.get("Location") == "/.web"
        self.post("/.web", check=405)

    def test_custom(self) -> None:
        """Custom web plugin."""
        self.configure({"web": {"type": "radicale.tests.custom.web"}})
        _, answer = self.get("/.web")
        assert answer == "custom"
        _, answer = self.post("/.web", "body content")
        assert answer == "echo:body content"

    def test_serve_resource_custom_mimetypes(self) -> None:
        """serve_resource must honor mimetypes and fallback_mimetype."""
        status, headers, _, _ = httputils.serve_resource(
            "radicale.web", "internal_data", "", "/.web/index.html")
        assert status == 200
        assert dict(headers)["Content-Type"] == "text/html"
        status, headers, _, _ = httputils.serve_resource(
            "radicale.web", "internal_data", "", "/.web/index.html",
            mimetypes={".html": "text/x-custom"})
        assert status == 200
        assert dict(headers)["Content-Type"] == "text/x-custom"
        status, headers, _, _ = httputils.serve_resource(
            "radicale.web", "internal_data", "", "/.web/index.html",
            mimetypes={}, fallback_mimetype="application/x-fallback")
        assert status == 200
        assert dict(headers)["Content-Type"] == "application/x-fallback"
