import ujson


class Stats():
    def __init__(self):
        self.filename = '/usr/stats.json'

        self.odometer = 0
        self.reboots = 0
        self.traffic = 0
        
        self.Load()

    def Load(self):
        try:
            with open(self.filename, "r") as sensors_file:
                stored_sensors = ujson.loads(sensors_file.read())

                for k in stored_sensors:                    
                    setattr(self, k, stored_sensors[k])

                sensors_file.close()
        except Exception:
            with open(self.filename, "w+") as sensors_file:
                print("Creating default sensors file...")
                json_object = ujson.dumps(self.__dict__)

                sensors_file.write(json_object)

                sensors_file.close()
    
    def Save(self):
        json_object = ujson.dumps(self.__dict__)

        with open(self.filename, "w+") as sensors_file:
            sensors_file.write(json_object)

            sensors_file.close()

    def Update(self, updates):
        for k in updates:
            self.__dict__[k] = updates[k]

        self.Save()
