from math import modf


class Ips_Protocol():
    def __init__(self, imei, ips_password):
        self.imei = imei
        self.ips_password = ips_password

    def make_login_packet(self):
        return '#L#{};{}\r\n'.format(self.imei, self.ips_password), '#AL#1\r\n'

    def make_data_packet(self, location_point):
        sensors_str = ''
        if len(location_point['sensors']) > 0:
            sensors_arr = []

            for k in location_point['sensors']:
                sensor_type = 1

                if isinstance(location_point['sensors'][k], float):
                    sensor_type = 2
                elif isinstance(location_point['sensors'][k], str):
                    sensor_type = 3

                sensors_arr.append('{}:{}:{}'.format(
                    k, sensor_type, location_point['sensors'][k]))

            sensors_str = ",".join(sensors_arr)

        date = '{:02d}{:02d}{:02d}'.format(
            location_point['date'][0], location_point['date'][1], location_point['date'][2])
        if date == '000000':
            date = 'NA'

        time = '{:02d}{:02d}{:02d}'.format(
            location_point['timestamp'][0], location_point['timestamp'][1], int(location_point['timestamp'][2]))
        if time == '000000':
            time = 'NA'

        latitude_tuple = modf(location_point['latitude'][1])
        new_lat = latitude_tuple[1]+float(str(latitude_tuple[0])[:6])

        lat = '{:02d}{:.4f}'.format(location_point['latitude'][0], new_lat)
        if lat == '000.0000':
            lat = 'NA'

        longitude_tuple = modf(location_point['longitude'][1])
        new_lon = longitude_tuple[1]+float(str(longitude_tuple[0])[:6])

        lon = '{:03d}{:.4f}'.format(location_point['longitude'][0], new_lon)
        if lon == '0000.0000':
            lon = 'NA'

        data_packet = '#D#{};{};{};{};{};{};{};{};{};{};{};NA;NA;NA;NA;{}\r\n'.format(
            # date
            date,
            # timestamp
            time,
            # lat
            lat, location_point['latitude'][2],
            # lon
            lon, location_point['longitude'][2],
            # other
            location_point['speed'], location_point['course'], location_point['altitude'], location_point['sats'],
            location_point['hdop'],
            # sensors
            sensors_str
        )

        return data_packet, '#AD#1\r\n'
