from config import Config as cfg
import pytz
from datetime import datetime
from dateutil.parser import parse


class Timezone:

    def __init__(self, app) -> None:
        self.app = app

    def datetime_by_tzone(self):
        tzone = cfg.timezone
        offset = None
        # Algunos casos donde el timezone es de la forma 4:30 y no se encuentra en timezones de pytz (GMT)
        if ":" in tzone:
            offset = tzone.split(":")[1]
            tzone = tzone.split(":")[0]
            if "+" in tzone:
                tzone = tzone.replace(tzone[-1], str(int(tzone[-1]) + 1))
        timezones_list = pytz.all_timezones
        tzones = [x if tzone in x else None for x in timezones_list]
        tzones = list(filter(None, tzones))
        server_timezone = pytz.timezone(tzones[0])
        self.app.logger.debug("Zona Horaria : {}".format(server_timezone))
        server_time = server_timezone.localize(datetime.utcnow())
        current_time = parse(server_time.strftime('%Y-%m-%d %H:%M:%S.%f %Z'))
        if offset:
            offset = pytz.FixedOffset((current_time.utcoffset().total_seconds() / 60 + float(offset)) * -1)
            offset = offset.utcoffset(datetime.utcnow())
            current_time = datetime.utcnow() + offset
        else:
            current_time = current_time.replace(tzinfo=None) - current_time.utcoffset()
        current_time = parse(current_time.strftime(cfg.time_pattern))
        self.app.logger.debug("Hora actual: {}".format(current_time))

        return current_time
