from typing import List, Tuple
from src.detections import (
    Detection,
    NumberDetection,
)
from src.string_replacements import replace_and_update
from src.replacers.interface import ReplacerInterface
import random
import string


def randomize_digits_in_text(text: str) -> str:
    result = ""

    for c in text:
        if c.isdigit():
            result += random.choice(string.digits)
        else:
            result += c

    return result


class NumberReplacer(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, NumberDetection):
                if text[start:end] not in already_replaced:
                    already_replaced[text[start:end]] = randomize_digits_in_text(
                        text[start:end]
                    )

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

        return replace_and_update(text, replacements, not_processed)