from datetime import datetime, timedelta
from browser import document, window
from modal import Modal


class StorageHooks:
    selector = '[data-vt-role="hook"]'

    def __init__(self, element):
        self.element = element
        self.hook_id = self.element.attrs['data-vt-call']
        self.expire_str = self.element['data-vt-hook-expired']
        self.storage = window.localStorage

        self.init_hook_click()
        self.check_expiration()
        self.clean_tag_hook()

    def init_hook_click(self):
        hook_click = document.select(f'[data-vt-hook-click="{self.hook_id}"]')

        if hook_click:
            hook_click[0].bind('click', self.save_consent)
        
        back_clicks = document.select('[data-vt-hook-back]')
        
        for back in back_clicks:
            back.bind('click', self.go_back)

    def save_consent(self, event=None):
        self.storage.setItem(self.hook_id, self.get_expire_date())

    def check_expiration(self):
        stored_value = self.storage.getItem(self.hook_id)

        if stored_value and self.is_expired(stored_value):
            return

        Modal.call_show(self.hook_id)

    def is_expired(self, datetime_str) -> bool:
        date = datetime.strptime(datetime_str, '%d/%m/%Y, %H:%M:%S')
        now = datetime.now()

        if date < now:
            return False

        return True

    def get_expire_date(self):
        time_delta = timedelta()
        if self.expire_str.endswith('d'):
            days = int(self.expire_str[:-1])
            time_delta = timedelta(days=days)
        elif self.expire_str.endswith('h'):
            days = int(self.expire_str[:-1])
            time_delta = timedelta(hours=days)
        elif self.expire_str.endswith('m'):
            days = int(self.expire_str[:-1])
            time_delta = timedelta(minutes=days)
        elif self.expire_str.endswith('s'):
            days = int(self.expire_str[:-1])
            time_delta = timedelta(seconds=days)

        time_delta += datetime.now()
        return time_delta.strftime('%d/%m/%Y, %H:%M:%S')

    def go_back(self):
        window.history.back()

    def clean_tag_hook(self):
        self.element.remove()

    @classmethod
    def initialize(cls):
        elements = document.select(cls.selector)
        for element in elements:
            cls(element)


StorageHooks.initialize()
