import subprocess
from typing import Optional

from clarabot_nano.core.config.utility import get_local_license_validity
from clarabot_nano.core.state.update.base import AbstractStateUpdateHandler


class NewLicense(AbstractStateUpdateHandler):
    HANDLER_KEY = "new_license"

    def get_new_state_kvs(self, data: dict) -> Optional[dict]:
        vendor = self._s.get("vendor")
        if not isinstance(vendor, str):
            raise Exception("Can't set license without vendor")
        license = data.get("license")
        if not isinstance(license, str):
            raise Exception("Invalid license")
        if license:
            validity = get_local_license_validity(vendor, license)
            if isinstance(validity, str):
                raise Exception(f"License validity failure: {validity}")
            if self._s.get("license") == license:
                raise Exception("Same license already set")
        else:  # allow unsetting
            validity = "missing", None
        hook_vendor_data = self._l.get("hook_vendor_data")
        if not hook_vendor_data:
            raise Exception("No vendor data hook is configured")
        hook_vendor_data = [hook_vendor_data] if isinstance(hook_vendor_data, str) else list(hook_vendor_data)
        hook_vendor_data.append(license)
        if subprocess.check_call(hook_vendor_data) != 0:
            raise Exception("Vendor data hook set returned error")
        return {
            "license": license or None,
            "license_local_validity": validity[0],
            "license_expiration": validity[1],
            "license_server_validity": "unknown",
        }
