import ujson
from misc import Power


class Settings():
    def __init__(self):
        self.filename = '/usr/settings.json'
        self.server = 'monitoring.logictrail.com.ua'
        self.port = 20332

        self.pin = ''

        self.apn = 'internet'
        self.apn_login = ''
        self.apn_password = ''

        # security
        self.auth_phone = '380672571279'
        self.tpass = '11111'
        self.ips_password = 'IPS'

        # 15 minutes timeout
        self.timeout = 600

        self.distance = 300
        self.course_delta = 10

        self.acc_refill_timeout = 1000
        self.acc_compare_treshold = 10

        self.Load()

    def Load(self):
        try:
            with open(self.filename, 'r') as settings_file:
                stored_settings = ujson.loads(settings_file.read())

                for k in stored_settings:
                    if k not in ['filename', 'server', 'pin', 'apn', 'apn_login', 'apn_password', 'auth_phone', 'tpass', 'ips_password']:
                        if stored_settings[k] == '':
                            stored_settings[k] = 0
                        setattr(self, k, int(stored_settings[k]))
                    else:
                        setattr(self, k, stored_settings[k])

                settings_file.close()
        except Exception as ex:
            # if hasattr(ex, 'message'):
            #    print('sett1', ex.message)
            # else:
            #     print('sett1', ex)

            with open(self.filename, 'w+') as settings_file:
                print('Creating default configuration...')
                json_object = ujson.dumps(self.__dict__)

                settings_file.write(json_object)

                settings_file.close()

    def Save(self):
        json_object = ujson.dumps(self.__dict__)

        with open(self.filename, 'w+') as settings_file:
            settings_file.write(json_object)

            settings_file.close()

    def Update(self, update):
        for k in update:
            print('trying', k)
            if k not in ['filename', 'server', 'pin', 'apn', 'apn_login', 'apn_password', 'auth_phone', 'tpass', 'ips_password']:
                try:
                    if update[k] == '':
                        update[k] = 0

                    setattr(self, k, int(update[k]))
                except Exception as ex:
                    if hasattr(ex, 'message'):
                        print(ex.message)
                    else:
                        print(ex)
            else:
                setattr(self, k, update[k])
        self.Save()
        # Power.powerRestart()
