#!/usr/bin/env python

import pytz
import sys
import time

from datetime import datetime as dt
from threading import Thread

from aman.com.DwdCrawler import DwdCrawler
import aman.config.Weather

class Weather(Thread):
    def __init__(self, config : aman.config.Weather.Weather):
        Thread.__init__(self)

        self.NextUpdate = dt.utcfromtimestamp(int(time.time()))
        self.LastUpdateTried = None
        self.StopThread = False
        self.Provider = None

        if 'DWD' == config.Provider.upper():
            self.Provider = DwdCrawler()
        elif 'NONE' != config.Provider.upper():
            sys.stderr.write('Invalid or unknown weather-provider defined')
            sys.exit(-1)

        self.setDaemon(True)
        self.start()

    def currentClock():
        clock = dt.utcfromtimestamp(int(time.time())).replace(tzinfo = pytz.UTC)
        return clock

    def run(self):
        while False == self.StopThread and None != self.Provider:
            now = Weather.currentClock()

            # check if an update is required
            if None != self.Provider.UpdateTime and self.Provider.UpdateTime > now:
                time.sleep(1)
                continue

            if None == self.LastUpdateTried or self.LastUpdateTried <= now:
                if True == self.Provider.receiveWindData():
                    self.NextUpdate = self.Provider.UpdateTime
                    print('Received new wind data')