import hashlib
import uuid
import secrets
import random

from .config import token_config


class PasswordModule:

    @staticmethod
    def generate_random_uu_id(str_std: bool = True):
        return str(uuid.uuid4()) if str_std else uuid.uuid4()

    @staticmethod
    def generate_token(length=32) -> str:
        letters = "abcdefghijklmnopqrstuvwxyz"
        merged_letters = [letter for letter in letters] + [
            letter.upper() for letter in letters
        ]
        token_generated = secrets.token_urlsafe(length)
        for i in str(token_generated):
            if i not in merged_letters:
                token_generated = token_generated.replace(
                    i, random.choice(merged_letters), 1
                )
            return token_generated
        raise ValueError("EYS_0004")

    @classmethod
    def generate_access_token(cls) -> str:
        return cls.generate_token(int(token_config.ACCESS_TOKEN_LENGTH))

    @classmethod
    def generate_refresher_token(cls) -> str:
        return cls.generate_token(int(token_config.REFRESHER_TOKEN_LENGTH))

    @staticmethod
    def create_hashed_password(domain: str, id_: str, password: str) -> str:
        return hashlib.sha256(f"{domain}:{id_}:{password}".encode("utf-8")).hexdigest()

    @classmethod
    def check_password(cls, domain, id_, password, password_hashed) -> bool:
        return cls.create_hashed_password(domain, id_, password) == password_hashed
