from django.core.management.base import BaseCommand
import fstools
import json
from pygal.models import is_valid_area, Item

from ._private import KEY_USERDATA_VERSION
from ._private import KEY_USERDATA_FAVOURITE
from ._private import KEY_USERDATA_TAGS
from ._private import KEY_USERDATA_UPLOAD

KEY_REL_PATH = '_rel_path_'
KEY_FAVOURITE = '_favourite_of_'
KEY_TAG = '_tags_'
KEY_UPLOAD = '_upload_'


class Command(BaseCommand):
    help = 'Convert userdata from old pygal to JSON-Format.'

    def add_arguments(self, parser):
        parser.add_argument('folder', nargs='+', type=str)

    def handle(self, *args, **options):
        data = {}
        data[KEY_USERDATA_VERSION] = 1
        path = options['folder'][0]
        for f in fstools.filelist(path, '*.json'):
            with open(f, 'r') as fh:
                o = json.load(fh)
            _rel_path_ = o.get(KEY_REL_PATH)
            _favourite_of_ = o.get(KEY_FAVOURITE)
            _tags_ = o.get(KEY_TAG)
            _upload_ = o.get(KEY_UPLOAD)
            if _rel_path_:
                try:
                    i = Item.objects.get(rel_path=_rel_path_)
                except Item.DoesNotExist:
                    self.stderr.write(self.style.ERROR('%s does not exist. No data taken over!' % _rel_path_))
                else:
                    if _favourite_of_:
                        for username in _favourite_of_:
                            if KEY_USERDATA_FAVOURITE not in data:
                                data[KEY_USERDATA_FAVOURITE] = {}
                            if username not in data[KEY_USERDATA_FAVOURITE]:
                                data[KEY_USERDATA_FAVOURITE][username] = []
                            data[KEY_USERDATA_FAVOURITE][username].append(_rel_path_)
                    if len(_tags_):
                        new_tags = []
                        for t in _tags_:
                            new_tag = {}
                            new_tag['text'] = _tags_[t].get('tag')
                            #
                            x = _tags_[t].get('x')
                            y = _tags_[t].get('y')
                            w = _tags_[t].get('w')
                            h = _tags_[t].get('h')
                            if x is not None and y is not None and w is not None and h is not None:
                                width = i.item_data.width
                                height = i.item_data.height
                                x1 = int(x * width)
                                y1 = int(y * height)
                                x2 = x1 + int(w * width)
                                y2 = y1 + int(h * height)
                                if is_valid_area(x1, y1, x2, y2):
                                    new_tag['topleft_x'] = x1
                                    new_tag['topleft_y'] = y1
                                    new_tag['bottomright_x'] = x2
                                    new_tag['bottomright_y'] = y2
                                    new_tags.append(new_tag)
                                else:
                                    self.stderr.write(self.style.ERROR('Coordinates are not valid for %s. Not transferred!' % _rel_path_))
                            else:
                                new_tags.append(new_tag)
                        if len(new_tags) > 0:
                            if KEY_USERDATA_TAGS not in data:
                                data[KEY_USERDATA_TAGS] = {}
                            data[KEY_USERDATA_TAGS][_rel_path_] = new_tags
                    if len(_upload_):
                        if KEY_USERDATA_UPLOAD not in data:
                            data[KEY_USERDATA_UPLOAD] = {}
                        data[KEY_USERDATA_UPLOAD][_rel_path_] = _upload_
        self.stdout.write(json.dumps(data, indent=4, sort_keys=True))
