import logging

from django.contrib.auth import get_user_model
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from django.template.loader import render_to_string
from django.core.mail import EmailMessage
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.conf import settings

from rest_framework_simplejwt.tokens import RefreshToken

from tagulous.models import TagModel

User = get_user_model()


class AccountActivationTokenGenerator(PasswordResetTokenGenerator):
    def _make_hash_value(self, user, timestamp):
        return f"{user.pk}{timestamp}{user.full_name}"


account_activation_token = AccountActivationTokenGenerator()


def get_tokens_for_user(user):
    refresh = RefreshToken.for_user(user)

    return {
        'refresh': str(refresh),
        'access': str(refresh.access_token),
    }


def get_auth_token(client, email, password):
    credentials = {
        'email': email,
        'password': password,
    }
    response = client.post('/api/v1/token/', credentials, format='json')
    if response.status_code == 200:
        return response.data['access']
    else:
        # logging.error(f"User {email} was refused a token: {response.content}")
        return None


def create_active_user(email, password):
    user = User.objects.create_user(email=email, password=password)
    user.is_active = True
    user.save()
    return user


def create_admin_user(email, password):
    user = User.objects.create_user(email=email, password=password)
    user.is_staff = True
    user.is_active = True
    user.save()
    return user


def send_verification_email(request, user):
    try:
        current_site = get_current_site(request)
        subject = 'Activa Tu Cuenta'
        message = render_to_string('email_verification.html', {
            'user': user,
            'domain': current_site.domain,
            'uid': urlsafe_base64_encode(force_bytes(user.pk)),
            'token': account_activation_token.make_token(user),
        })
        email = EmailMessage(
            subject, message, to=[user.email]
        )
        email.send()
        logging.info(f"Verification email sent to {user.email}")
    except Exception as e:
        logging.error(f"Could not sent verification email to: {user.email}")


def reformat_google_taxonomy(file_name):
    """
    Read from flat text file
    Create Herarchical Tag for each line
    """

    base = settings.BASE_DIR + '/../datasets/'
    counter = 0
    source_file_path = base + file_name
    destination_file_path = base + 'ALT' + file_name

    source_file = open(source_file_path, 'rt')
    destination_file = open(destination_file_path, 'wt')

    for line in source_file.readlines():
        line = line.replace(' > ', '/')
        destination_file.write(line)

