from typing import List, Tuple
from src.detections import (
    Detection,
    UserDetection,
)
from src.string_replacements import replace_and_update
from src.replacers.interface import ReplacerInterface
from random_username.generate import generate_username


class UserReplacer(ReplacerInterface):
    def __init__(self):
        pass

    def replace(
        self, text: str, detections: List[Tuple[int, int, Detection]]
    ) -> Tuple[str, List[Tuple[int, int, Detection]]]:
        replacements = []
        not_processed = []

        already_replaced = dict()

        for item in detections:
            start, end, detection = item

            if isinstance(detection, UserDetection):
                if text[start:end] not in already_replaced:
                    username = "@" + generate_username(1)[0]
                    already_replaced[text[start:end]] = username

                replacements.append((start, end, already_replaced[text[start:end]]))
            else:
                not_processed.append(item)

        return replace_and_update(text, replacements, not_processed)