import logging
import stripe
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.db import models
from django.conf import settings

from .models import Address, User

logger = logging.getLogger(__name__)


@receiver(post_save, sender=User, dispatch_uid='user_saved')
def user_saved(sender, instance, created, **kwargs):
    logger.info('User was saved')
    if created or not instance.stripe_id:
        stripe.api_key = settings.STRIPE_API_KEY
        response = stripe.Customer.create(
            name=instance.first_name + instance.last_name
        )
        instance.stripe_id = response['id']
        instance.save()
