import logging

from typing import Union, AnyStr, Type

from staff.celery_app import app
from staff.lib.tasks import LockedTask
from staff.oebs.controllers import linkers
from staff.oebs.controllers.linkers import LinkerBaseT
from staff.oebs.models import library, OEBSModelBaseT

logger = logging.getLogger(__name__)


@app.task(ignore_result=True)
class LinkTask(LockedTask):
    def get_linker(self, model: Union[AnyStr, Type[OEBSModelBaseT]]) -> Type[LinkerBaseT]:
        return linkers.library.get(model)

    def locked_run(self, object_id=None, model=None):
        logging.info('Linking model {}'.format(model))
        linker = self.get_linker(library[model])
        return linker.link() if linker else None

    def get_lock_name(self, *args, **kwargs):
        name = self.__class__.__name__
        model = kwargs.get('model')
        return '{}_{}'.format(name, model)
