import os
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta

from montyalex.cache_tools import add_to_cache, remove_item_from_cache
from montyalex.console_tools import richconsole, success_stm
from .helpdirs import remove_formated__dir


print = richconsole.print

START = datetime.now()

def create_date_directories(
        range_: int = 1, four_weeks: bool = False, parent: str = None, silent: bool = False):
    add_to_cache(key='_datedirs_', value=f'{START:%Y-%m-%d}', silent=True)
    new_date = START
    for i in range(range_ * 12):
        if four_weeks:
            new_date += timedelta(days=28)
        else:
            new_date = START + relativedelta(months=i)
        formatted_date = new_date.strftime('%Y-%m-%d')
        if parent:
            os.makedirs(os.path.join(os.getcwd(), parent, formatted_date), exist_ok=True)
        else:
            os.makedirs(os.path.join(os.getcwd(), formatted_date), exist_ok=True)
        if not silent:
            cwd_ = os.path.abspath(parent) if parent else os.getcwd()
            print(
                f'{success_stm}, Created {formatted_date!r} in {cwd_!r}')

def remove_date_directories(
        range_: int = 1, four_weeks: bool = False, parent: str = None, silent: bool = False):
    remove_item_from_cache(key='_datedirs_', silent=True)
    if parent:
        remove_formated__dir(parent, silent)

        new_date = START
        for i in range(range_ * 12):
            if four_weeks:
                new_date += timedelta(days=28)
            else:
                new_date = START + relativedelta(months=i)
            formatted_date = new_date.strftime('%Y-%m-%d')
            formatted_directory = os.path.join(os.getcwd(), formatted_date)
            formatted_directory = os.path.join(os.getcwd(), parent)
            if not os.path.exists(formatted_directory) and not silent:
                print(
                    f'{success_stm}, Removed {formatted_date!r} from {formatted_directory!r}')
        if not os.path.exists(parent) and not silent:
            print(f'{success_stm}, Removed {parent!r} from {os.getcwd()!r}')
    else:
        for i in range(range_ * 12):
            new_date = START + relativedelta(months=i)
            formatted_date = new_date.strftime('%Y-%m-%d')
            formatted_directory = os.path.join(os.getcwd(), formatted_date)
            remove_formated__dir(formatted_directory, silent)
            if not os.path.exists(formatted_directory) and not silent:
                print(f'{success_stm}, Removed {formatted_date!r} from {os.getcwd()!r}')
