# -*- encoding: utf-8 -*-
import requests

from suite_py.__version__ import __version__
from suite_py.lib.handler.github_handler import GithubHandler
from suite_py.lib.handler.okta_handler import Okta


class BackstageResponseError(Exception): ...


class Backstage:
    _okta: Okta
    _github: GithubHandler

    def __init__(self, config, okta: Okta, tokens=None):
        backstage_url = config.user["backstage_url"]
        self._baseurl = f"{backstage_url}/api/entity-locking"
        self._timeout = config.user["backstage_timeout"]
        self._okta = okta

        if tokens is not None:
            self._github = GithubHandler(tokens)

    def lock_project(self, project, env):
        return self.send_request(
            "post",
            "/projects/manage-lock",
            json={
                "project": project,
                "status": "locked",
                "user": self._get_user(),
                "environment": env,
            },
        )

    def unlock_project(self, project, env):
        return self.send_request(
            "post",
            "/projects/manage-lock",
            json={
                "project": project,
                "status": "unlocked",
                "user": self._get_user(),
                "environment": env,
            },
        )

    def status(self, project, env):
        return self.send_request(
            "get", f"/projects/check?project={project}&environment={env}"
        )

    def check(self):
        response = self.send_request("get", "/ping", timeout=(2, self._timeout))
        assert response.text == "pong"

    def send_request(self, method, endpoint, data=None, json=None, timeout=None):
        response = requests.request(
            method,
            f"{self._baseurl}{endpoint}",
            headers=self._headers(),
            data=data,
            json=json,
            timeout=(timeout or self._timeout),
        )

        if response.status_code == 200:
            return response

        raise BackstageResponseError(
            f"Got unexpected status code from Backstage: {response.status_code}"
        )

    def _get_user(self):
        return self._github.get_user().login

    def _headers(self):
        return {
            "User-Agent": f"suite-py/{__version__}",
            "Authorization": f"Bearer {self._okta.get_id_token()}",
        }
