from usr import file_logger
from usr import file_queue
import usr.uasyncio as asyncio
from usr import sensor
from usr import packet_ips
from usr import stats as intern
from usr import settings as setts
from usr import uart
from usr import nmea
from usr import helpers
from machine import ExtInt
from machine import Timer
from machine import I2C
from machine import Pin
# from machine import WDT
from misc import USB
from misc import ADC
from misc import Power

import osTimer
import math
import quecgnss
# import utime
import sms
import modem
import net
import sim
import checkNet
import dataCall
import usocket
# import gc
import ble
import ubinascii

# gc.enable()


sensors_sources_data = {}
movement_status = 0

# reboot every 24 hours
# wdt = WDT(86400)


def ble_callback(args):
    global sensors_sources_data

    if args[0] == 0 and args[1] == 0:
        res = ble.getStatus()
        # print('getStatus', res)

        res = ble.setScanParam(1, 0x50, 0x100, 2, 0)
        if res != 0:
            print('ble client set scan-parameters failed.')
        else:
            print('ble client set scan-parameters successful.')

        res = ble.setScanFilter(0)
        if res != 0:
            print('ble client set scan-filter failed.')
        else:
            print('ble client set scan-filter successful.')

        ble.scanStart()

    sens_list = sensors.Get()
    sources = []

    for k in sens_list:
        if k is not None and sens_list[k]['visible'] == 1:
            try:
                sources.append(sens_list[k]['source'])
            except KeyError:
                pass

    if args[0] == 19 and len(args) == 9:
        addr = '{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}'.format(
            args[5][5], args[5][4], args[5][3], args[5][2], args[5][1], args[5][0])

        # print('{}\t{}'.format(addr, args[8]))

        # ble_list[addr] = ubinascii.hexlify(args[8].encode('utf-8'))
        if addr in sens_list:
            sensors_sources_data[addr] = ubinascii.hexlify(args[8])
            print('ble sensor', addr, 'found')
        # sensors_values[addr] = args[8]


USB_PORT = USB()
# D_HIGH = Pin(Pin.GPIO9, Pin.IN, Pin.PULL_DISABLE, 0)
D_HIGH = Pin(Pin.GPIO9, Pin.IN, Pin.PULL_DISABLE, 0)

OUT = Pin(Pin.GPIO28, Pin.OUT, Pin.PULL_DISABLE, 0)

ADC_INPUTS = ADC()
ADC_INPUTS.open()

acc_filtered = []


class CurrentPoint():
    def __init__(self):
        self.latitude = [0, 0.0, 'N']
        self.longitude = [0, 0.0, 'W']

        self.timestamp = [0, 0, 0.0]

        self.date = [0, 0, 0]

        self.hdop = 0.0
        self.sats = 0
        self.speed = 0.0

        self.course = 0

        self.altitude = 0.0

        self.sensors = {}

        self.previous_course = 0
        self.distance = 0
        self.prev_latitude = [0, 0.0, 'N']
        self.prev_longitude = [0, 0.0, 'W']
        self.valid = 0


def distance_diff(location):
    lon1 = location.longitude[0] + (location.longitude[1] / 60)
    lat1 = location.latitude[0] + (location.latitude[1] / 60)

    lon2 = location.prev_longitude[0] + (location.prev_longitude[1] / 60)
    lat2 = location.prev_latitude[0] + (location.prev_latitude[1] / 60)

    distance = 0

    if lat1 != 0.0 or lon1 != 0.0 or lat2 != 0.0 or lon2 != 0.0:
        radius = 6371  # km
        dlat = math.radians(lat2 - lat1)
        dlon = math.radians(lon2 - lon1)
        a = (math.sin(dlat / 2) * math.sin(dlat / 2) +
             math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) *
             math.sin(dlon / 2) * math.sin(dlon / 2))
        c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
        d = radius * c

        distance = d*1000

    return distance


async def scan_sensors():
    global sensors_sources_data, acc_counter, internal_stats, movement_status, sensors

    while True:
        sensors_sources_data['adc0'] = ADC_INPUTS.read(ADC_INPUTS.ADC0)
        sensors_sources_data['adc1'] = ADC_INPUTS.read(ADC_INPUTS.ADC1)
        sensors_sources_data['adc2'] = ADC_INPUTS.read(ADC_INPUTS.ADC2)
        sensors_sources_data['vbat'] = Power.getVbatt()
        sensors_sources_data['usb'] = USB_PORT.getStatus()
        sensors_sources_data['d_high'] = D_HIGH.read()
        sensors_sources_data['d_out'] = OUT.read()
        sensors_sources_data['reboots'] = internal_stats.reboots
        sensors_sources_data['acc_c'] = acc_counter
        sensors_sources_data['p_on'] = Power.powerOnReason()
        sensors_sources_data['mov'] = movement_status

        sens = sensors.Get()
        for k in sens:
            try:
                if helpers.not_in_range(sensors_sources_data[sens[k]['source']], sens[k]['lower_limit'], sens[k]['upper_limit']):
                    print('sensor {} not in range, min{}/max{}: {}'.format(
                        k, sens[k]['lower_limit'], sens[k]['upper_limit'], sensors_sources_data[sens[k]['source']]))

                    # make_packet('sens_{}'.format(k))
            except KeyError:
                pass

        await asyncio.sleep(0.1)


def sms_receiver_callback(args):
    phone_number, sms_text, sms_length = sms.searchTextMsg(args[1])

    if settings.auth_phone == '' or settings.auth_phone in phone_number:
        out.write('Incoming SMS {} from {}, sms_len is {}'.format(
            sms_text, phone_number, sms_length))

        out.read(sms_length, sms_text, phone_number)

    sms.deleteMsg(1, 4)


my_gps = nmea.NmeaParser()
my_gps.SENTENCE_LIMIT = 90


async def find_location():
    global current_location, movement_status

    out.write('Scanning for satellites.')

    while True:
        gps_data = quecgnss.read(2048)

        for x in gps_data[1]:
            my_gps.update(x)

        if my_gps.valid:
            current_location.longitude = my_gps.longitude
            current_location.latitude = my_gps.latitude

            current_location.date = my_gps.date
            current_location.timestamp = my_gps.timestamp

            current_location.hdop = float("{:.2f}".format(my_gps.hdop))
            current_location.sats = my_gps.satellites_in_use
            current_location.speed = float(
                "{:.2f}".format(my_gps.speed[2]))
            current_location.course = my_gps.course

            current_location.altitude = my_gps.altitude

            if current_location.valid == 0:
                out.write('Location found!')
                current_location.valid = 1

                current_location.prev_latitude = current_location.latitude
                current_location.prev_longitude = current_location.longitude

                make_packet('loc')
            else:
                if abs(current_location.course - current_location.previous_course) >= settings.course_delta and current_location.speed > 5:
                    out.write(
                        'Course changed for more then {} degrees, making packet.'.format(settings.course_delta))
                    movement_status = 1
                    make_packet('degree')

                current_location.previous_course = current_location.course

                if current_location.speed > 7:
                    movement_status = 1

                    current_location.distance += int(
                        distance_diff(current_location))

                    internal_stats.odometer += current_location.distance
                    print('odometer', internal_stats.odometer)
                    internal_stats.Save()

                # print('current_location.distance:', current_location.distance)
                # print('settings.distance:', settings.distance)

                if current_location.distance > settings.distance:
                    out.write(
                        'Distance changed for more then {} meters, making packet.'.format(settings.distance))
                    movement_status = 1
                    make_packet('distance')
                    current_location.distance = 0

        if pdp is False and sim_detected is True:
            out.write('Turning modem off...')
            net.setModemFun(0)

            out.write('Turning modem on...')
            net.setModemFun(1)

            # asyncio.sleep(5)

        await asyncio.sleep(1)


async def ping():
    global pdp, sock

    while True:
        await asyncio.sleep(180)

        stagecode, subcode = checknet.wait_network_connected()

        if stagecode == 3 and subcode == 1 and pdp is True and sock.getsocketsta() == 4:
            try:
                out.write('Ping...')

                n = sock.send('#P#\r\n')
                internal_stats.traffic += n

                reply = sock.readline()

                if reply == b'#AP#\r\n':
                    out.write('...ponG')
            except Exception as ex:
                out.write('Error sending "PING" packet')
                if hasattr(ex, 'message'):
                    out.write('{} {}'.format(ex.message))
                else:
                    out.write('{} {}'.format(ex))


async def check_queue():
    global pdp, sock

    while fq.count() != 0 and pdp is True and sock.getsocketsta() == 4:
        packet = fq.pop()

        # try:
        out.write('Sending packet...')
        data_packet, expected_datapacket_reply = ips.make_data_packet(
            packet)

        try:
            n = sock.send(data_packet)
            internal_stats.traffic += n

            reply = sock.readline()

            if reply.decode() == expected_datapacket_reply:
                fq.delete()

                out.write('Messages left to send: {}'.format(fq.count()))
        except Exception as ex:
            out.write('Error sending packet from history')
            if hasattr(ex, 'message'):
                out.write('{} {}'.format(ex.message))
                fl.add(ex.message)
            else:
                out.write('{} {}'.format(ex))
                fl.add(ex)

            # return

        await asyncio.sleep(1)


def make_packet(args):
    global current_location, sensors_sources_data, pdp, fq

    if args not in ['loc', 'degree', 'distance']:
        args = 'timeout'
        current_location.latitude = current_location.prev_latitude
        current_location.longitude = current_location.prev_longitude
    else:
        current_location.latitude = my_gps.latitude
        current_location.longitude = my_gps.longitude

        current_location.prev_latitude = current_location.latitude
        current_location.prev_longitude = current_location.longitude

    out.write('Point creation source: {}'.format(args))

    # scan_sensors()

    sens_list = sensors.Get()
    for k in sens_list:
        if k is not None and sens_list[k]['visible'] == 1:
            try:
                value = sensors_sources_data[sens_list[k]['source']]
                if sens_list[k]['stop'] > 0:
                    value = int(
                        value[sens_list[k]['start']:sens_list[k]['stop']].decode("utf-8"), 16)

                    # byteorder is big where MSB is at start, big/little
                    # value = int.from_bytes(value, "big")

                if len(sens_list[k]['formula']) > 3:
                    formula = sens_list[k]['formula'].replace(
                        'x', str(value))

                    try:
                        current_location.sensors[k] = eval(formula)
                    except Exception:
                        current_location.sensors[k] = 0
                else:
                    current_location.sensors[k] = value
            except KeyError:
                pass

    current_location.sensors['point_cs'] = args

    for k in current_location.sensors:
        out.write('{}: {}'.format(k, current_location.sensors[k]))

    out.write('Trying to send packet...')

    try:
        data_packet, expected_datapacket_reply = ips.make_data_packet(
            current_location.__dict__)

        n = sock.send(data_packet)
        internal_stats.traffic += n

        if pdp is True:
            reply = sock.readline()

            if reply.decode() == expected_datapacket_reply:
                # fq.delete()

                out.write('Packet sent OK')

        else:
            fq.add(current_location)

        internal_stats.Save()
    except Exception as ex:
        out.write(
            'Server connection error, saving current packet to history')
        fq.add(current_location)

        if hasattr(ex, 'message'):
            out.write(ex.message)
            fl.add(ex.message)
        else:
            out.write(ex)
            fl.add(ex)

        out.write('{} packets in history'.format(fq.count()))


def data_call_cb(args):
    global pdp, sock

    if args[1] == 1:
        stagecode, subcode = checknet.wait_network_connected()

        if stagecode == 3 and subcode == 1:
            out.write('Network connection restored!')
            pdp = True

    else:
        out.write('Network not connected.')
        pdp = False
        sock.close()

        # net.setModemFun(1)


async def socket_connect():
    global pdp, sock

    while True:
        if sock.getsocketsta() != 4:
            try:
                sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
                out.write('Connecting to {}:{}...'.format(
                    settings.server, settings.port))
                sockaddr = usocket.getaddrinfo(
                    settings.server, settings.port)[0][-1]

                sock.connect(sockaddr)

                login_packet, expected_login_result = ips.make_login_packet()

                n = sock.send(login_packet)
                internal_stats.traffic += n

                data = sock.readline()

                if data.decode() == expected_login_result:
                    out.write('Server login OK!')
                    pdp = True
            except Exception:
                out.write('Connection failed, waiting 5 seconds to reconnect.')

        await asyncio.sleep(5)


async def fill_acc(timeout, acc_filtered):
    global acc_counter
    while True:
        await asyncio.sleep_ms(timeout)

        acc_filtered.append(False)

        if len(acc_filtered) > 20:
            acc_filtered.pop(0)

        # print(acc_filtered)


def acc_cb(args):
    global accelerometer, acc_filtered, acc_counter

    if args[1] == 0:
        out.write('ACC interrupt')
        acc_counter += 1

        acc_filtered.append(True)
        if len(acc_filtered) > 20:
            acc_filtered.pop(0)

    read_data = bytearray(1)
    accelerometer.read(30, bytearray([0x17, 0]), 1, read_data, 1, 0)


MODEL = "BI868_FLEX"
VERSION = "0.0.9"

GREEN_BLINKER = Pin(Pin.GPIO31, Pin.OUT, Pin.PULL_DISABLE, 0)
RED_BLINKER = Pin(Pin.GPIO46, Pin.OUT, Pin.PULL_DISABLE, 0)

# 868 stuff


# accelerometer init start
ACC = ExtInt(ExtInt.GPIO8, ExtInt.IRQ_RISING_FALLING,
             ExtInt.PULL_DISABLE, acc_cb)
ACC.enable()
accelerometer = I2C(I2C.I2C0, I2C.FAST_MODE)
acc_counter = 0

r_data = bytearray(96)
accelerometer.read(30, bytearray([0x00, 0]), 1, r_data, 96, 0)
accelerometer.write(158, bytearray([0x18, 0]), 1, bytearray([0x42]), 1)

cnt3 = bytearray([0x9D, 0x85, 0x30, 0x3F, 0x3F,
                 0x02, 0x10, 0x00, 0x00, 0x02, 0x03])

accelerometer.write(158, bytearray([0x1A, 0]), 1, cnt3, 11)
accelerometer.write(158, bytearray([0x30, 0]), 1, bytearray([0x01]), 1)
# accelerometer.write(158, bytearray([0x18, 0]), 1, bytearray([0xC2]), 1)
accelerometer.write(158, bytearray([0x18, 0]), 1, bytearray([0xC7]), 1)

# accelerometer init end


IMEI = modem.getDevImei()

sensors = sensor.Sensors()
settings = setts.Settings()
out = uart.CicadaUart(MODEL, VERSION, IMEI, settings, sensors)
ips = packet_ips.Ips_Protocol(IMEI, settings.ips_password)
fq = file_queue.FileQueue()
fl = file_logger.FileLogger()

current_location = CurrentPoint()

internal_stats = intern.Stats()

pdp = False
sim_detected = False

checknet = checkNet.CheckNetwork(MODEL, VERSION)

sock = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)

GPS_PRESENT = quecgnss.init()
if GPS_PRESENT != 0:
    out.write('GPS module not found!')

sms.setSaveLoc("ME", "ME", "ME")
sms.setCallback(sms_receiver_callback)

event_loop = asyncio.get_event_loop()

internal_stats.reboots += 1
internal_stats.Save()

packet_timer = Timer(Timer.Timer1)
packet_timer.start(period=1000*settings.timeout,
                   mode=packet_timer.PERIODIC, callback=make_packet)


def movement_reset(arg):
    global movement_status
    movement_status = 0
    print('resetting movement status')


movement_reset_timer = osTimer()
movement_reset_timer.start(60000, 1, movement_reset)


async def blinkers():
    global pdp

    while True:
        # red blinker
        if int((ADC_INPUTS.read(ADC.ADC0)/10)*130) < 5000 or USB_PORT.getStatus() != 1:
            # power is off
            RED_BLINKER.write(1)
            await asyncio.sleep_ms(50)
            RED_BLINKER.write(0)
            await asyncio.sleep_ms(950)
        else:
            # power is on
            RED_BLINKER.write(1)

        # green blinker
        if pdp is False:
            GREEN_BLINKER.write(1)
        else:
            GREEN_BLINKER.write(1)
            await asyncio.sleep_ms(50)
            GREEN_BLINKER.write(0)
            await asyncio.sleep_ms(950)

        await asyncio.sleep(1)


async def bootstrap(settings):
    global sim_detected

    if len(settings.pin) > 0:
        res = sim.enablePin(settings.pin)
        if res == 0:
            res = sim.verifyPin(settings.pin)
            if res == 0:
                out.write('PIN ok')
            else:
                out.write('Wrong PIN')

    while sim.getStatus() != 1:
        net.setModemFun(0)
        await asyncio.sleep(3)
        net.setModemFun(1)
        await asyncio.sleep(3)
        out.write('Detecting SIM...')

    out.write('SIM is ready.')
    sim_detected = True

    net.setConfig(8, 1)

    dataCall.setCallback(data_call_cb)

    res = dataCall.start(1, 0, settings.apn, settings.apn_login,
                         settings.apn_password, 0)


async def ble_start_scan():
    try:
        print('stoppig scan')
        res = ble.scanStop()
        print(res)

        res = ble.clientInit(ble_callback)
        print(1, res)

        res = ble.gattStart()
        print(2, res)
    except Exception:
        print('stopped')
        ble.scanStop()


async def main():
    try:
        out.write('*************************')
        out.write('Model: {}'.format(MODEL))
        out.write('FW: {}'.format(VERSION))
        out.write('IMEI: {}'.format(IMEI))
        out.write('*************************')
        out.write('Reboots: {}'.format(internal_stats.reboots))
        out.write('Total bytes sent: {}'.format(internal_stats.traffic))
        out.write('Odometer: {}'.format(internal_stats.odometer))
        out.write('Power on reason: {}'.format(Power.powerOnReason()))

        GREEN_BLINKER.write(1)

        event_loop.create_task(find_location())

        event_loop.create_task(check_queue())

        event_loop.create_task(scan_sensors())

        event_loop.create_task(blinkers())

        event_loop.create_task(
            fill_acc(settings.acc_refill_timeout, acc_filtered))

        event_loop.create_task(bootstrap(settings))

        event_loop.create_task(socket_connect())

        event_loop.create_task(ping())

        event_loop.create_task(ble_start_scan())

        event_loop.run_forever()
    except Exception as ex:
        out.write('App error')
        if hasattr(ex, 'message'):
            out.write(ex.message)
            fl.add(ex.message)
        else:
            out.write(ex)
            fl.add(ex)

        Power.powerRestart()

asyncio.run(main())
