import time
import requests
import serial
import sys

'''
ser = serial.Serial('/dev/ttyAMA4', 115200, timeout=1)

class AT:
    def __init__(self, port='/dev/ttyAMA4', Baud_rate=115200):
        self.port = port
        self.rate = Baud_rate

    def AT_port(self):
        try:
            global ser
            ser = serial.Serial(self.port, self.rate, timeout=1)
            ser.write(b'AT\r\n')
            res_at = ser.readlines()[1].decode('utf-8').strip()
            if res_at == "OK":
                return True
        except serial.SerialException as e:
            sys.exit(e)


def AT_Commander(command):
        ser.write(command.encode())
        time.sleep(1)
        res = ser.readlines() #[1].decode('utf-8').strip()

        return res


def HTTPINIT():
    ser.write(b'AT+HTTPINIT\r\n')
    res_httpinit = ser.readlines()[1].decode('utf-8').strip()
    if res_httpinit == "ERROR":
        init_result = False
    else:
        init_result = True
    
    return init_result


class HTTPPARA:
    def __init__(self, url, auth_token):
        self.url = url
        self.auth_token = auth_token

    def PARA(self):
        #URL
        commandU = 'AT+HTTPPARA=URL,{}\r\n'.format(self.url)
        ser.write(commandU.encode())
        res_URL = ser.readlines()[1].decode('utf-8').strip()
        
        #content type
        commandT = 'AT+HTTPPARA=CONTENT,{}\r\n'.format("application/json")
        ser.write(commandT.encode())
        res_TYPE = ser.readlines()[1].decode('utf-8').strip()
        
        #Header
        commandH = 'AT+HTTPPARA=USERDATA,"Authorization: Bearer {}"\r\n'.format(self.auth_token)
        ser.write(commandH.encode())
        res_HDR = ser.readlines()[1].decode('utf-8').strip()

        if ((res_URL == "OK") and (res_HDR == "OK") and (res_TYPE == "OK")):
            para_result = True
        else:
            para_result = False
        
        return para_result


#retrieve server response header information
def HTTPHEAD():
    commandH = 'AT+HTTPHEAD\r\n'
    ser.write(commandH.encode())
    resH = ser.readlines() #[1].decode('utf-8').strip()
    
    return resH
    

def HTTPDATA(data):
    l = str(len(data))
    command = 'AT+HTTPDATA={},10\r\n'.format(l)
    ser.write(command.encode())
    res_httpdata = ser.readlines()[1].decode('utf-8').strip()
    if res_httpdata == 'DOWNLOAD':
        ser.write(data.encode())
        res_inputdata = ser.readlines()[1].decode('utf-8').strip()
        
    #fin_result = ser.readlines()[1].decode('utf-8').strip()
    #if (fin_result == 'OK'):
     #   return True
    #else:
        return res_inputdata #False
        


#HTTP response class
class HTTP_response:
    def __init__(self, status_code, text):
        self.status_code = status_code
        self.text = text


def HTTPACTION():
    global response_length
    command = 'AT+HTTPACTION=1\r\n' #post requests only
    ser.write(command.encode())
    time.sleep(1)
    res_action = ser.readlines()[1].decode('utf-8').strip()
    #if res_aciton == 'OK':
        #while True:
     #   line = ser.readlines() #.decode('utf-8').strip()

        #if not line.startswith("+HTTPACTION: "):
            #continue

        #res_callback = line.split(": ")[1]  # Extract the part after ": "
        #action, response_code, response_length = res_callback.split(",")[:3]

        #response_code = int(response_code)                
        #response_data = HTTPREAD(response_length)

        #action_result = HTTP_response(status_code=response_code, text=response_data)

    return res_action #action_result


def HTTPREAD(data_length):
    command = 'AT+HTTPREAD=0,{}\r\n'.format(data_length)
    ser.write(command.encode())
    #original - data_read = ser.readlines()[4].decode('utf-8').strip()
    res_read = ser.readlines()[1].decode('utf-8').strip()
    
    if res_read == 'OK':
        while True:
            line = ser.readline().decode('utf-8').strip()
            
            if line.startswith("+HTTPREAD: "):
                break
        
        line = ''
        while True:
            read_line = ser.readline().decode('utf-8').strip()

            if (read_line.startswith("+HTTPREAD: ")):
                break

            line = line + read_line
        
        return line


def HTTPTERM():
    command = 'AT+HTTPTERM\r\n'
    ser.write(command.encode())
    res_term = ser.readlines()[1].decode('utf-8').strip()
    if res_term == 'OK':
        return True
    else:
        return False



#initialize iot module
def iot_module_init():
    port_result = AT().AT_port()
    if (port_result):
        init_result = HTTPINIT()
    else:
        init_result = False

    return init_result



#Drone HTTP client
def anomaa_client1(auth_token, requestURL, requestBody):
    
    #set HTTP parameters
    para_result = HTTPPARA(url=requestURL, auth_token=auth_token).PARA()

    if (para_result):        
        HTTPDATA(requestBody)
        request_response = HTTPACTION(1)

        HTTPTERM()    
        
        return request_response
    else:
        return HTTP_response(500, "Internal server error")

'''

#Drone HTTP client
def anomaa_client(requestHeader, requestURL, requestBody):
    responseObject = requests.post(requestURL, data = requestBody, headers=requestHeader)

    return responseObject
