from django.core.management.base import BaseCommand

from tag.models import Tag
from transfer import models as legacy
from tqdm import tqdm


class Command(BaseCommand):
    help = 'Add tags translation from old db to new db'

    @staticmethod
    def humanisation_tag(self):
        """Humanisation for default values."""
        tags = Tag.objects.all()
        for tag in tqdm(tags):
            value = tag.label
            for k, v in value.items():
                if isinstance(v, str) and '_' in v:
                    sp = v.split('_')
                    v = ' '.join([sp[0].capitalize()] + sp[1:])
                    tag.label[k] = v
            tag.save()

    def handle(self, *args, **kwargs):
        """Translation for existed tags."""
        translation = legacy.MetadatumAliases.objects.all()
        # self.humanisation_tag()
        for trans in tqdm(translation):
            tag = Tag.objects.filter(value=trans.value).first()
            if tag:
                tag.label.update(
                    {trans.locale: trans.meta_alias}
                )
                tag.save()
