from django.conf import settings
from django.utils.functional import cached_property

from intranet.search.core.tvm import tvm2_client
from intranet.search.core.utils import http


class HelpClientApi:
    page_size: int = 100
    api_conf: dict = settings.ISEARCH['api']['help']
    forms_api_url: str = api_conf['forms'].url()
    form_api_url: str = api_conf['form'].url()

    @property
    def tvm_ticket(self):
        ticket = tvm2_client.get_service_ticket('help')
        return ticket

    @cached_property
    def session(self):
        session = http.create_session()
        session.headers.update({
            settings.TVM2_SERVICE_HEADER: self.tvm_ticket,
        })
        return session

    def fetch(self, url: str, **kwargs):
        response = http.call_with_retry(self.session.get, url, **kwargs)
        return response.json()

    def fetch_forms(self, page: int, filters: dict = {}):
        params = filters
        params.update({"_limit": self.page_size, "_page": page})

        return self.fetch(self.forms_api_url, params=params)

    def fetch_form(self, form_id: int):
        return self.fetch(self.form_api_url.format(id=form_id))
