from datetime import datetime

from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.core.mail import EmailMultiAlternatives
from django.db import models
from django.dispatch import receiver
from django.template.loader import render_to_string
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django_rest_passwordreset.signals import reset_password_token_created
from rest_framework.permissions import IsAdminUser
import uuid
from config.settings.base import DEFAULT_FROM_EMAIL
# from verify_trusted.users.tasks import send_email


class User(AbstractUser):
	"""Default user for Verify Trusted."""

	#: First and last name do not cover name patterns around the globe
	name = models.CharField(_("Name of User"), blank=True, max_length=255)
	fail_to_login = models.IntegerField(default=0, blank=True)
	ip = models.CharField(max_length=20, blank=True, null=True, default=None)
	first_name = None  # type: ignore
	last_name = None  # type: ignore

	def get_absolute_url(self):
		"""Get url for user's detail view.

		Returns:
			str: URL for user detail.

		"""
		return reverse('users:detail', kwargs={'username': self.username})


def user_directory_path(instance, filename):
	timestr = str(datetime.now().strftime('%Y_%m_%d_%H_%M_%S'))
	new_filename = filename.split(".")
	return 'user/{0}_{1}.{2}'.format(
		instance.user.id, timestr, new_filename[len(new_filename) - 1]
	)


class Profile(models.Model):
	user = models.OneToOneField(
		User, on_delete=models.CASCADE, primary_key=True, related_name='profile'
	)
	first_name = models.CharField(max_length=50, blank=True, default='')
	last_name = models.CharField(max_length=50, blank=True, default='')
	photo = models.ImageField(
		upload_to=user_directory_path, blank=True, null=True, max_length=500
	)
	address = models.CharField(max_length=255, blank=True, default='')
	language = models.CharField(max_length=20, blank=True, default='en')
	due_date = models.DateField(blank=True, null=True)
	unsubscribe_email = models.BooleanField(blank=True, default=False, null=True)
	connect_token = models.CharField(max_length=36,default='',blank=True,null=True)
	shopify_url = models.CharField(max_length=250,default='',blank=True,null=True)
	shopify_token = models.CharField(max_length=250,default='',blank=True,null=True)
	charge_id = models.CharField(max_length=250,default='',blank=True,null=True)
	phone_number = models.CharField(
		max_length=17, blank=True, null=True
	)  # validators should be a list

	active = models.BooleanField(default=True)

	def __str__(self):
		return "{}'s profile".format(self.user)

	def save(self, *args, **kwargs):
		if not self.connect_token:
			self.connect_token = str(uuid.uuid4())
		super().save(*args, **kwargs)


@receiver(reset_password_token_created)
def password_reset_token_created(
	sender, instance, reset_password_token, *args, **kwargs
):
	"""
	Handles password reset tokens
	When a token is created, an e-mail needs to be sent to the user
	:param sender: View Class that sent the signal
	:param instance: View Instance that sent the signal
	:param reset_password_token: Token Model Object
	:param args:
	:param kwargs:
	:return:
	"""
	is_admin = True if IsAdminUser in sender.permission_classes else False
	if settings.IS_PRODUCTION:
		send_to_email = [reset_password_token.user.email]
	else:
		send_to_email = settings.DEFAULT_SEND_TO_EMAIL
	if is_admin:
		reset_password_url = "{}?token={}".format(
			# instance.request.build_absolute_uri(reverse('password_reset:reset-password-confirm')),
			'https://%s/check-register' % settings.ADMIN_CLIENT_NAME,
			reset_password_token.key,
		)
		email_context = {
			'static_url': settings.AWS_S3_CUSTOM_DOMAIN,
			'redirect_url': reset_password_url,
			'client_url': settings.CLIENT_NAME,
			'name': reset_password_token.user.username,
			'is_admin': 1
		}
		template = render_to_string(
			'users/email/day1_tpl.html',
			context=email_context,
		)
		msg = EmailMultiAlternatives(
			# title:
			# title:
			'Welcome to Verify Trusted',
			# message:
			'Welcome',
			# from:
			DEFAULT_FROM_EMAIL,
			# to:
			send_to_email,
			bcc=['info@verifytrusted.com', 'verifytrusted.support@sphinxjsc.com'],
		)
	else:
		reset_password_url = "{}?token={}".format(
			# instance.request.build_absolute_uri(reverse('password_reset:reset-password-confirm')),
			'https://%s/resetpassword' % settings.ADMIN_CLIENT_NAME,
			reset_password_token.key,
		)
		email_context = {
			'email': reset_password_token.user.email,
			'redirect_url': reset_password_url,
			'static_url': settings.AWS_S3_CUSTOM_DOMAIN,
			'client_url': settings.CLIENT_NAME,
		}
		template = render_to_string(
			'users/email/email_reset_pass.html',
			context=email_context,
		)
		msg = EmailMultiAlternatives(
			# title:
			'Password Reset for {title}'.format(title='Verify Trusted'),
			# message:
			'Reset password',
			# from:
			DEFAULT_FROM_EMAIL,
			# to:
			send_to_email,
			bcc=['info@verifytrusted.com', 'verifytrusted.support@sphinxjsc.com'],
		)
	msg.attach_alternative(template, "text/html")
	msg.send()
