from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import User
from hookmigration.models import Transient
from hookmigration.peewee_models import CustomauthMyuser, CustomersCustomer, CustomersAddress
from django.core.management.base import BaseCommand
from hookmigration.settings import *
from apps.customer.models import Profile
from django.db import transaction, IntegrityError

from oscar.core.loading import get_model
from stripe_payment.models import StripeCustomer, StripeSource
from progressbar import ProgressBar
import re

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


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

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

    def handle(self, *args, **options):
        done = 0
        problems = []
        country = Country.objects.get(pk='SG')
        with transaction.atomic():
            users = CustomauthMyuser.select()
            progress = ProgressBar(max_value=users.count())
            for old_user in users:
                # Create the user
                user_content_type = ContentType.objects.get_for_model(User)
                profile = old_user.profile[0] if old_user.profile else None
                # Check for duplicate emails.
                if User.objects.filter(email=old_user.email).exists():
                    problems.append('Duplicate account - {}'.format(old_user.email))
                    continue
                new_user = User(
                    username=old_user.email,
                    email=old_user.email,
                    first_name=profile.first_name[0:29] if profile else old_user.email.split('@')[0][0:29],
                    last_name=profile.last_name if profile else old_user.email.split('@')[0],
                    is_active=old_user.is_active,
                    date_joined=old_user.created_at,
                    password=old_user.password
                )
                new_user.save()
                # Add the transient.
                Transient.objects.create(
                    content_type=user_content_type,
                    old_pk=old_user.id,
                    new_pk=new_user.pk
                )
                # Add the profile.
                Profile.objects.create(
                    user=new_user,
                    phone=self._format_phone_number(profile.phone) if profile else None,
                    country=country
                )
                done += 1
                progress.update(done)
        print('==========================================================================================')
        print(problems)
        print('==========================================================================================')
