from celery import chain

from waldur_core.core import executors
from waldur_core.core import tasks as core_tasks
from waldur_core.core import utils as core_utils
from waldur_core.structure import executors as structure_executors

from . import models
from .tasks import SetInstanceErredTask


class VolumeCreateExecutor(executors.CreateExecutor):
    @classmethod
    def get_task_signature(cls, volume, serialized_volume, **kwargs):
        return chain(
            core_tasks.BackendMethodTask().si(
                serialized_volume, 'create_volume', state_transition='begin_creating'
            ),
            core_tasks.PollRuntimeStateTask()
            .si(
                serialized_volume,
                backend_pull_method='pull_volume_runtime_state',
                success_state='available',
                erred_state='error',
            )
            .set(countdown=30),
        )


class VolumeDeleteExecutor(executors.DeleteExecutor):
    @classmethod
    def get_task_signature(cls, volume, serialized_volume, **kwargs):
        if volume.backend_id:
            return core_tasks.BackendMethodTask().si(
                serialized_volume, 'delete_volume', state_transition='begin_deleting'
            )
        else:
            return core_tasks.StateTransitionTask().si(
                serialized_volume, state_transition='begin_deleting'
            )


class VolumeDetachExecutor(executors.ActionExecutor):
    @classmethod
    def get_task_signature(cls, volume, serialized_volume, **kwargs):
        return chain(
            core_tasks.BackendMethodTask().si(
                serialized_volume, 'detach_volume', state_transition='begin_updating'
            ),
            core_tasks.PollRuntimeStateTask()
            .si(
                serialized_volume,
                backend_pull_method='pull_volume_runtime_state',