from enum import IntEnum
from wizart.desktop.projects_registry import ProjectsAggregator

import auth_session
from command import Command, CommandExecutionStatus, ExecuteCommandError


class AssetBrowserEntityType(IntEnum):
    Unknown = 0
    Assets = 1
    Episodes = 2
    Scenes = 3
    Series = 4
    EpisodeAssets = 5
    AssetCharfxVariant = 6


class AssetBrowserCommand(Command):
    entity_type = AssetBrowserEntityType.Unknown

    def __init__(self, name, project_id):
        super(AssetBrowserCommand, self).__init__()
        self.session = auth_session.get_prodtrack_session()
        self.name = name
        self.project_id = project_id
        self.task_params = {}

    @classmethod
    def command_type_as_dict(cls):
        result = {}
        result["name"] = cls.name
        result["label"] = cls.label
        result["entity_type"] = int(cls.entity_type)
        return result

    @classmethod
    def get_command_type_by_name(cls, command_name):
        for clsobj in cls.__subclasses__():
            if clsobj.name == command_name:
                return clsobj

    def post_to_fs(self, url, json):
        fs_ctrl_session = auth_session.get_fs_ctrl_session()
        self.log.debug("%s" % json)
        response = fs_ctrl_session.post(url, json=json)
        if response.status_code != 200:
            format_args = dict(
                url=url,
                args=str(json),
                status=response.status_code,
                reason=response.reason,
            )
            raise ExecuteCommandError(
                "Failed request to url '{url}' with args: '{args}', status: {status}, reason: {reason} ".format(
                    **format_args
                )
            )
        self.task_params[response.json()["id"]] = {"name": self.name, "args": json}


class CreateEpisodeAssetCommand(AssetBrowserCommand):
    name = "create_episode_asset"
    label = "Create Episode Asset(s) On Disk"
    entity_type = AssetBrowserEntityType.EpisodeAssets

    def __init__(self, project_id, **kwargs):
        super(CreateEpisodeAssetCommand, self).__init__(kwargs.get("name"), project_id)
        self.command_arguments = kwargs

    def execute(self):
        self.log.info("Create: {}".format(self.name))
        project = ProjectsAggregator.get_project_by_id(self.project_id)
        if not project:
            self.log.error("It is not possible to get prodtrack config for project")
            return CommandExecutionStatus.Failed

        url = "http://fs_ctrl.burut.net/api/command/{project}/create_episode_asset".format(
            project="dev_xeash_" + project.name if project.name.startswith("sandbox") else project.name
        )
        self.post_to_fs(url, self.command_arguments)
        return CommandExecutionStatus.Success


class CreateCarfxVariantCommand(AssetBrowserCommand):
    name = "create_asset_variant"
    label = "Create Asset(s) Variant On Disk"
    entity_type = AssetBrowserEntityType.AssetCharfxVariant

    def __init__(self, name, asset_name, charfx_type, project_id):
        super(CreateCarfxVariantCommand, self).__init__(name, project_id)
        self.asset_name = asset_name
        self.charfx_type = charfx_type

    def execute(self):
        self.log.info("Create: {}".format(self.name))

        project = ProjectsAggregator.get_project_by_id(self.project_id)
        if not project:
            self.log.error("It is not possible to get prodtrack config for project")
            return CommandExecutionStatus.Failed

        command_arguments = {}
        command_arguments["asset"] = self.asset_name
        command_arguments["name"] = self.name
        command_arguments["type"] = self.charfx_type
        url = "http://fs_ctrl.burut.net/api/command/{project}/create_asset_variant".format(
            project=project.name
        )
        self.post_to_fs(url, command_arguments)
        return CommandExecutionStatus.Success
