import gps
import cellular
import machine
import socket

from blink import blink

APN = "YOUR_APN_HERE"

class A9G:

    def __init__(self):
        self.device_id = "pumpkinthecat_duplicate"

    """
    Registers to the cellular network
    Connects to GPRS
    Turns on the GPS
    """
    def initialize_device(self):
        animation = "|/-\\"
        idx = 0
        while not cellular.is_network_registered():
            print("wait for network to register ",
                  animation[idx % len(animation)] ,
                  cellular.get_signal_quality(),
                  end="\r")
            blink(100)
            idx += 1

        # gps.on()
        cellular.gprs(APN, "", "")
        machine.watchdog_on(30)

    def watchdog_reset(self):
        machine.watchdog_reset()
    def set_idle(self, value):
        machine.set_idle(value)
        gps.off()

    def gps(self, value):
        if value is True:
            gps.on()
        else:
            gps.off()

    def get_device_summary(self):
        return "Signal Quality: {}, Registered: {}".format(cellular.get_signal_quality(), cellular.is_network_registered())
    def reset(self):
        machine.reset()
    """
    Gets server IP (time to complete: 1second)
    Gets current GPS location
    Sends location to the server
    """
    def report_location_to_server(self, host_addr, port):
        print("reporting location")
        if not cellular.is_network_registered():
            print('Please initialize the device using initialize_device() before trying to call this method.')
            return False

        # the host IP can change; we look up the ip every time we try to make a request
        try:
            host_ip = socket.getaddrinfo(host_addr, port)[0][-1][0]
        except OSError as err:
            print("There was an error resolving the host IP", err)
            return False

        try:
            gps.get_location()

        except OSError:
            gps.on()

        current_location = gps.get_location()
        nmea = gps.nmea_data()[2]
        print("Current GPS Location: ", current_location)
        print("NMEA GGA data", nmea)
        lat = current_location[0]
        lon = current_location[1]
        battery_percent = machine.get_input_voltage()[1]
        print("Battery Level: {}".format(battery_percent))
        POST_QUERY = 'POST /?id={}&lat={}&lon={}&batt={} HTTP/1.1\r\nHost: {}:{}\r\n\r\n'.format(
            self.device_id, lat, lon, battery_percent, host_ip, port)

        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            print("Socket successfully created")
        except Exception as err:
            print("socket creation failed with error %s" % (err))
            return False

        try:
            s.connect((host_ip, port))
            s.send(bytes(POST_QUERY, 'utf-8'))
        except OSError as err:
            print("Failed to connect / send to server. {}", err)

        # TODO: try this to avoid a9g crashes: https://github.com/pulkin/micropython/issues/50#issuecomment-708664801
        resp = s.recv(256)

        print(resp)
        s.close()

        blink(100)

        return

