from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend
try:
    import requests
except ModuleNotFoundError as e:
    pass
from django.conf import settings

class EmailBackend(ModelBackend):
    def fetch_fortnox(self, customer_id=None):
        """ Fetch all active customers from Fortnox API. Return as dict keyed on email."""
        res = None
        customers = {}
        headers = {"Access-Token":settings.FORTNOX_ACCESS_TOKEN,
           "Client-Secret":settings.FORTNOX_CLIENT_SECRET,
           "Content-Type":"application/json",
           "Accept":"application/json" }
        if customer_id: #We already have id, use that to update info in local db
            res = requests.get(f"https://api.fortnox.se/3/customers/{customer_id}?filter=active", headers=headers)
            res = res.json()
            res['Customer'] = [res['Customer']]
        else:
            res = requests.get("https://api.fortnox.se/3/customers?filter=active", headers=headers)
        
        for customer in res['Customer']:
            customers[customer['Email']] = customer
        return customers

    def authenticate(self, username=None, password=None, **kwargs):
        UserModel = get_user_model()
        try:
            user = UserModel.objects.get(email=username)
        except UserModel.DoesNotExist:
            customers = self.fetch_fortnox()
          #  import pdb;pdb.set_trace()
            if username in customers:
                if ' ' in customers[username]['Name']:
                    (fname,lname) = customers[username]['Name'].split(' ',1)
                    user = User.objects.create_user(email=username,
                                     first_name=fname,
                                     last_name=lname,
                                     fortnox_external_id=int(customers[username]['CustomerNumber']))
                    return user
                else:
                    fname = customers[username]['Name']
                    user = User.objects.create_user(username=username,
                                 email=username,
                                 first_name=fname,
                                 fortnox_external_id=int(customers[username]['CustomerNumber']))
                    return user
            return None
        else:
            customer = self.fetch_fortnox(customer_id=user.fortnox_external_id)
            if not customer:
                user.is_active=False
                return None
            user.first_name = customer[user.email]['Name'] #TODO synd more data
            user.save()
            if user.check_password(password):
                return user
        return None
