from django.db.models import Model, CharField, ForeignKey, CASCADE, DateTimeField
from django.contrib.auth import get_user_model

from dbsettings.functions import getValue

from smsotp.helpers import generate_token
from core.modules.sms import get_default_sms_provider

# Create your models here.

class OTPToken(Model):
    token = CharField(max_length=32, default=generate_token)
    user = ForeignKey(get_user_model(), CASCADE)
    creation = DateTimeField(auto_now_add=True)

    def send_sms(self, text=getValue("smsotp.text", "Your authentication token is:"), number=None):
        if "_TOKEN_" in text:
            text = text.replace("_TOKEN_", self.token)
        else:
            text = f"{text} {self.token}"
        
        number = number or self.user.profile.mobile

        provider = get_default_sms_provider()

        provider.sendSMS(number, text)