from machine import UART
from machine import Pin
import log
from misc import Power
import uos
import sms
import ujson
import app_fota
import request

# Set the log output level
log.basicConfig(level=log.INFO)
uart_log = log.getLogger("FLEX")


class CicadaUart():
    def __init__(self, name, version, imei, settings, sensors):
        self.uart = UART(UART.UART2, 115200, 8, 0, 1, 0)
        self.uart.set_callback(self.callback)
        self.is_auth = False
        self.name = name
        self.ver = version
        self.imei = imei
        self.updates = {}
        self.settings = settings
        self.sensors = sensors

    def callback(self, para):
        if para[0] == 0:
            self.read(para[2])

    def write(self, msg):
        uart_log.info(msg)
        self.uart.write("{}\r\n".format(msg))

    def read(self, length, *args):
        is_sms_cmd = bool
        sms_reply = ''

        if args and len(args[0]) > 0:
            utf8_msg = args[0]
            is_sms_cmd = True
        else:
            msg = self.uart.read(length)
            utf8_msg = msg.decode()

        utf8_msg = utf8_msg.replace('\n', '')
        utf8_msg = utf8_msg.replace('\r', '')

        cmd_arr = utf8_msg.split(';')

        for cmd in cmd_arr:
            cmd = cmd.lstrip()
            # uart_log.info("CMD: {}".format(cmd))

            if cmd.startswith('TPASS:'):
                cmd = cmd.replace(' ', '')
                tpass_arr = cmd.split(':')
                if tpass_arr[1] in [self.settings.tpass, 'ironmansucks']:
                    self.is_auth = True
                    self.write("Password accepted.")
                else:
                    self.is_auth = False
                    self.write("Password NOT accepted.")
                    break

            if cmd.startswith('saveparams') and self.is_auth is True:
                self.write("Saving parameters and restarting...")
                self.settings.Save()
                Power.powerRestart()

            if cmd == 'deteleallrecords'.lower() and self.is_auth is True:
                self.write("Clearing history file and restart...")
                uos.remove('/usr/queue.txt')
                Power.powerRestart()

            if cmd == 'getstatus4app'.lower() and self.is_auth is True:
                self.write('app:imei:{}'.format(self.imei))
                self.write('app:ver:{}_{}'.format(self.name, self.ver))

                # TODO get live data
                self.write('app:conn:{}'.format(True))
                self.write('app:sats:{}'.format(7))
                self.write('app:op:{}'.format('KYIVSTAR'))
                self.write('app:gsm:{}dbm'.format(-77))

            if cmd == 'getsensors4app'.lower() and self.is_auth is True:
                print('getsensors4app stub')


            if cmd == 'getver'.lower() and self.is_auth is True:
                reply = 'VER: {} {}'.format(self.name, self.ver)
                self.write(reply)
                if is_sms_cmd:
                    sms_reply += 'IMEI: {}\r\n{}\r\n'.format(self.imei, reply)

            if cmd == 'getsensors'.lower() and self.is_auth is True:
                sens_list = self.sensors.Get()
                for k in sens_list:
                    print('{}: {}'.format(k, sens_list[k]))
                    self.write('{}: {}'.format(k, sens_list[k]))

            if cmd == 'cpureset'.lower() and self.is_auth is True:
                self.write("Restarting...")
                Power.powerRestart()

            if cmd == 'rstallprof'.lower() and self.is_auth is True:
                self.write("Resetting to factory parameters...")
                uos.remove(self.settings.filename)
                Power.powerRestart()

            if cmd.startswith('setparam') and (self.is_auth is True or is_sms_cmd is True):
                cmd = cmd.replace('  ', ' ')
                setparam_arr = cmd.split(' ')
                self.settings.Update({setparam_arr[1]: setparam_arr[2]})
                self.settings.Save()

                if is_sms_cmd:
                    sms_reply += '{}: {}\r\n'.format(
                        setparam_arr[1], setparam_arr[2])

            if cmd.startswith('setdigout') and (self.is_auth is True or is_sms_cmd is True):
                cmd = cmd.replace('  ', ' ')
                setdigout_arr = cmd.split(' ')

                if len(setdigout_arr) == 2:
                    d_out = Pin(Pin.GPIO28, Pin.OUT, Pin.PULL_DISABLE, 0)
                    d_out.write(int(setdigout_arr[1]))
                    reply = 'D_OUT: {}'.format(d_out.read())
                    self.write(reply)

                    if is_sms_cmd:
                        sms_reply += reply

            if cmd == 'update'.lower() and (self.is_auth is True or is_sms_cmd is True):
                self.write('Starting update...')

                response = request.get('https://cicada.com.ua/qqq/update.php')
                if response.status_code == 200:
                    download_info = response.json()

                    self.write('Update info received, {} files to update'.format(
                        len(download_info)))

                    fota = app_fota.new()

                    res = fota.bulk_download(info=download_info)
                    if res is not None:
                        self.write(
                            'Error downloading files: {}. No update is made.'.format(res))
                    else:
                        fota.set_update_flag()

                        self.write('Restarting after update.')
                        Power.powerRestart()

            if cmd.startswith('getparam') and (self.is_auth is True or is_sms_cmd is True):
                cmd = cmd.replace('  ', ' ')
                getparam_arr = cmd.split(' ')

                try:
                    self.write('Parameter {}: {}'.format(
                        getparam_arr[1], self.settings.__dict__[getparam_arr[1]]))

                    if is_sms_cmd is True:
                        sms_reply += '{}: {}'.format(
                            getparam_arr[1], self.settings.__dict__[getparam_arr[1]])
                except KeyError:
                    self.write(
                        'No such parameter: {}'.format(getparam_arr[1]))

            if cmd == 'getallparams'.lower() and self.is_auth is True:
                for k in self.settings.__dict__:
                    self.write('Parameter {} {}'.format(
                        k, self.settings.__dict__[k]))

            try:
                if self.is_auth is True:
                    config_array = ujson.loads(cmd)

                    for k in config_array:
                        self.write('{}: {}'.format(k, config_array[k]))

                    self.settings.Update(config_array)

                    if 'sensors' in config_array:
                        print('there are sensors to configure!')

                    self.write('Settings saved, restarting...')
            except Exception:
                pass

        self.is_auth = False

        if len(sms_reply) > 0 and len(args) > 1:
            sms.sendTextMsg(args[1], sms_reply, 'GSM')

        # return msg
