
import tornado.ioloop
import tornado.httpclient
import tornado.web
import json
import joblib
import sys

import pandas as pd

arguments = sys.argv
lib = arguments[1]
model = joblib.load('./models/' + lib)
head_names=["received_bytes","send_bytes","port_duration","total_duration","jitter","differents_port"]



class GenericHandler(tornado.web.RequestHandler):

    TelegramBot=""
    ChatTelegramId=""
    message = "Alerta por escaneo. Puertos UDP escaneados desde la IP: "

    def send_telegram(self,ip):
        
        url = f"https://api.telegram.org/bot{self.TelegramBot}/sendMessage" 
        data = {"chat_id": self.ChatTelegramId, "text": self.message + ip} 
        headers = {"Content-Type": "application/json"}
        body = json.dumps(data) 

        http_client = tornado.httpclient.AsyncHTTPClient()  
        try:
            response = http_client.fetch(
                url, 
                method="POST",
                body=body, 
                headers=headers,
            )
        except:
            pass
        finally:
            http_client.close()

    def post(self):
        
        plain_text = self.request.body.decode('utf-8')
        metrics = plain_text.split("||")[0]
        ip_src = plain_text.split("||")[1]

        check_data = list(map(lambda x: float(x), metrics.split(',')))
        df_predict = pd.DataFrame([check_data])
        df_predict.columns = head_names
        pre = model.predict(df_predict)
        result = pre[0]
        self.set_header("Content-Type", "text/plain")
        self.write(str(result))
        if round(result) == 1:
            self.send_telegram(ip_src)
        self.finish()

        
def make_app():
    return tornado.web.Application([
        (r"/check", GenericHandler), 
    ])


def main():
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

if __name__ == "__main__":
    main()
