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

from typing import Self, Any
from Utils.Check import Check
from Utils.Utils import Utils
from Utils.Patterns import RE
from re import Match as REMatch
from re import Pattern as REPattern
from re import compile as re_compile

class RouteModel:
    
    def __init__(self:Self, inputs:str|list|tuple) -> None:

        self.method:str
        self.request:REPattern
        self.controller:str
        self.action:str
        self.path:str|None
        self.variables:tuple[str] = tuple()
        self.permissions:list[str] = []
        self.done:bool = False

        if Check.is_string(inputs):
            inputs = RE.ROUTE_ITEM.match(inputs).groups()

        if Check.is_array(inputs):

            self.done = True
            (
                self.method, self.request, self.action, self.controller, self.path, self.permissions
            ) = (lambda method, request, controller, action, path, permissions:(
                method.lower(), 
                re_compile(r'^' + RE.ROUTE_RE_FORMAT.sub(
                    self.format_request_item, 
                    RE.STRING_VARIABLES.sub(self.__add_variable, request)
                ) + (r'' if path else ('' if request[-1] == '/' else r'\/') + r'?$')), 
                controller, 
                action, 
                path, 
                (
                    [] if not permissions else 
                    str(permissions).split(",") if Check.is_string(permissions) else 
                    list(permissions) if Check.is_array(permissions) else 
                [])
            ))(*inputs)

    def __add_variable(self:Self, key:str) -> str:

        self.variables += (key,)

        return r'([^\/]+)'
    
    @staticmethod
    def format_request_item(matches:REMatch) -> str:

        character:str = matches.group(2)

        return '\\' + character if character else matches.group(1)

