from django.core.management.base import BaseCommand
from django.contrib.contenttypes.models import ContentType
from django.db import transaction
from hookmigration.models import Transient
from hookmigration.peewee_models import CustomersCustomer
from django.contrib.auth.models import User
from oscar.core.loading import get_model
import crayons
from progressbar import ProgressBar
import re

UserAddress = get_model('address', 'UserAddress')
Country = get_model('address', 'Country')


class Command(BaseCommand):
    help = 'Migrate addresses'

    def _format_phone_number(self, number):
        phone = re.sub(r'\W+', '', number)
        if phone.startswith('65'):
            return '+' + phone
        return '+65' + phone

    def handle(self, *args, **options):

        total = CustomersCustomer.select().count()
        finished = 0
        progress = ProgressBar(max_value=total)
        country = Country.objects.filter(iso_3166_1_a2='SG').first()
        user_content_type = ContentType.objects.get_for_model(User)
        address_content_type = ContentType.objects.get_for_model(UserAddress)
        missing = []
        with transaction.atomic():
            for customer in CustomersCustomer.select():
                new_user_transient = Transient.objects.filter(content_type=user_content_type).filter(
                    old_pk=customer.user_id).first()
                if not new_user_transient:
                    missing.append(customer)
                    continue
                new_user = User.objects.filter(pk=new_user_transient.new_pk).first()

                # Create the address.
                new_address = UserAddress(
                    first_name=customer.first_name,
                    last_name=customer.last_name,
                    line1=customer.line1,
                    line2=customer.line2,
                    line3='',
                    line4=country.name,
                    postcode=customer.postcode,
                    phone_number=self._format_phone_number(customer.phone),
                    is_default_for_shipping=1,
                    country=country,
                    user=new_user,
                )
                new_address.save()

                # Get the other addresses
                err_hash = '#'
                err_count = 1
                for old_address in customer.addresses:
                    new_new_address = UserAddress(
                        first_name=customer.first_name,
                        last_name=customer.last_name,
                        line1=old_address.line1,
                        line2=old_address.line2,
                        line3=err_count * err_hash,  # This is to avoid the hash checking failures
                        line4=country.name,
                        state=country.name,
                        postcode=old_address.postcode,
                        phone_number=self._format_phone_number(customer.phone),
                        is_default_for_shipping=0,
                        country=country,
                        user=new_user,
                    )
                    new_new_address.save()
                    err_count += 1
                    Transient.objects.create(
                        content_type=address_content_type,
                        old_pk=old_address.id,
                        new_pk=new_new_address.pk
                    )
                finished += 1
                progress.update(finished)

        print('Below customer are missing')
        print('======================================================================================')
        from pprint import pprint
        pprint(missing)
