# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.core.management.base import BaseCommand

from core.models import (
    Person, Person2Company, Person2Country, Person2Person, Declaration)
from core.utils import ceil_date
from tasks.models import PersonDeduplication, AdHocMatch
from django.db import connection


FIELDS_TO_CONCATENATE = [
    "reputation_assets_en",
    "reputation_sanctions_en",
    "reputation_crimes_en",
    "reputation_manhunt_en",
    "reputation_convictions_en",
    "wiki_en",
    "reputation_assets_uk",
    "reputation_sanctions_uk",
    "reputation_crimes_uk",
    "reputation_manhunt_uk",
    "reputation_convictions_uk",
    "wiki_uk",

    "also_known_as_uk",
    "also_known_as_en",
]

FIELDS_TO_UPDATE = [
    "is_pep",
    "photo",
    "dob",
    "city_of_birth_uk",
    "city_of_birth_en",
]


class Command(BaseCommand):
    help = ('Takes finished tasks for persons deduplication and applies '
            'to the Person model')

    def add_arguments(self, parser):
        # Named (optional) arguments
        parser.add_argument(
            '--real_run',
            action='store_true',
            dest='real_run',
            default=False,
            help='Apply deduplication results for real',
        )

    def handle(self, *args, **options):
        def _fetch_person(task, pk):
            try:
                return Person.objects.get(pk=pk)
            except Person.DoesNotExist:
                self.stderr.write(
                    "\tperson with id {} doesn't exist, skipping".format(pk)
                )

            return None

        def _delete_person(task, pk):
            person = _fetch_person(task, pk)
            if person:
                self.stdout.write(
                    "\tdeleting person {} with id {}, imported={}".format(
                        person.full_name, person.pk, person.imported)
                )

                if options["real_run"]:
                    person.delete()