#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from typing import Self, Any, Optional
from Interfaces.FormatModuleInterface import FormatModuleInterface
from Utils.Patterns import RE
from Utils.Check import Check
from Utils.Utils import Utils

class RandomFormat:

    def __init__(self:Self, 
        format:FormatModuleInterface, 
        options:Optional[dict[str, Any|None]] = None
    ) -> None:
        self.format:FormatModuleInterface = format

    def get(self:Self, 
        i:int, 
        inputs:str|list[Any|None], 
        shared:dict[str, Any|None] = {}, 
        fragments:list[str] = []
    ) -> str:
        return self.format.execute(i, Utils.get_random(self.format.get_list(i, (
            inputs.split("|") if Check.is_string(inputs) else 
            inputs[0] if Check.is_array(inputs[0]) else 
        ""))), shared, fragments)
    
    def check(self:Self, 
        i:int, 
        string:str, 
        inputs:str|list[Any|None], 
        shared:dict[str, Any|None] = {}, 
        fragments:list[str] = []
    ) -> int:
        
        has_empty:bool = False
        option:str
        
        for option in self.format.get_list(i, (
            inputs.split("|") if Check.is_string(inputs) else 
            inputs[0] if Check.is_array(inputs[0]) else 
        "")):
            if option == "":
                if not has_empty:
                    has_empty = True
                continue

            if RE.FRAGMENT_VARIABLES.match(self.format.set_fragments_level(option, fragments)):
                return self.format.get_check_length(i, string, option, shared, fragments, False)

            length:int = self.format.prepare_result(string, option, shared)

            if length != -1:
                return length
            
        return 0 if has_empty else -1