from biolib import api
from biolib.biolib_api_client import JobDict
from biolib.jobs.job_result import JobResult
from biolib.typing_utils import Optional


class Job:

    def __init__(self, uuid: str, auth_token: Optional[str] = None):
        self._uuid: str = uuid
        self._auth_token: Optional[str] = auth_token

        self._job_dict: Optional[JobDict] = None
        self._result: Optional[JobResult] = None

    def __str__(self) -> str:
        return self._uuid

    @property
    def result(self) -> JobResult:
        if not self._result:
            self._result = JobResult(job_uuid=self._uuid, job_auth_token=self._auth_token)

        return self._result

    def get_stdout(self) -> bytes:
        return self.result.get_stdout()

    def get_stderr(self) -> bytes:
        return self.result.get_stderr()

    def get_exit_code(self) -> int:
        return self.result.get_exit_code()

    def save_files(self, output_dir: str) -> None:
        self.result.save_files(output_dir=output_dir)

    def get_status(self) -> str:
        return self._get_job_dict(force_refetch=True)['state']

    def _get_job_dict(self, force_refetch: bool = False) -> JobDict:
        if not self._job_dict or force_refetch:
            job_dict: JobDict = api.client.get(
                url=f'/jobs/{self._uuid}/',
                headers={'Job-Auth-Token': self._auth_token} if self._auth_token else None,
            ).json()
            self._job_dict = job_dict

        return self._job_dict
