#!/usr/bin/env python3
import rclpy
import json
import random
import threading
import time
import hashlib
import requests

from paho.mqtt import client as mqtt_client
from rclpy.node import Node
from interface.msg import ROUTE
from interface.msg import GATHER

broker = "36.153.162.171"
# broker = "192.168.3.241"
port = 61883
topic = "/vehicle/ctrl/V020002"
# generate client ID with pub prefix randomly
client_id = f"python-mqtt-{random.randint(0, 100)}"

need_pub = 0
gather = -1
file_name = ""
post_file_name = ""


def md5_file(file_path):
    hash_md5 = hashlib.md5()
    with open(file_path, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()


def download_file(url, save_path):
    response = requests.get(url, stream=True)  # 开启stream模式，以便逐步下载文件
    if response.status_code == 200:
        with open(save_path, "wb") as f:
            for chunk in response.iter_content(
                chunk_size=8192
            ):  # 分块读取数据，避免内存占用过大
                f.write(chunk)
        print(f"文件下载成功，已保存到 {save_path}")
    else:
        print(f"文件下载失败，状态码 {response.status_code}")


def connect_mqtt() -> mqtt_client:
    def on_connect(client, userdata, flags, rc):
        if rc == 0:
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)

    client = mqtt_client.Client(client_id)
    client.on_connect = on_connect
    client.connect(broker, port)
    return client


def on_message(client, userdata, msg):
    global need_pub
    global gather
    global file_name
    print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic")
    json_data = json.loads(msg.payload.decode())

    if json_data["command"] == "distribute":
        str = json_data["value"]
        result = str.split(",")
        file_name = "common/txt/gps_load_now.txt"
        download_file(result[0], file_name)
        now_md5 = md5_file(file_name)
        if now_md5 != result[1]:
            print("md5 不一致")
        need_pub = 1
        print(json_data["command"])
    if json_data["command"] == "gather":
        gather = json_data["value"]
        print(json_data["command"])


def subscribe(client: mqtt_client):
    client.subscribe(topic)
    client.on_message = on_message


def run():
    client = connect_mqtt()
    subscribe(client)
    client.loop_forever()


class RouteNode(Node):
    def __init__(self, name):
        super().__init__(name)
        self.get_logger().info("大家好，我是%s!" % name)
        self.route_publisher_ = self.create_publisher(ROUTE, "ROUTE", 10)
        self.gather_publisher_ = self.create_publisher(GATHER, "GATHER", 10)
        self.route_publisher_timer_ = self.create_timer(
            1, self.route_publisher_timer_callback
        )
        self.gather_publisher_timer_ = self.create_timer(
            1, self.gather_publisher_timer_callback
        )

    def route_publisher_timer_callback(self):
        global need_pub
        global file_name
        if need_pub == 1:
            need_pub = 0
            msg = ROUTE()  # 构造消息
            msg.file = file_name
            self.route_publisher_.publish(msg)  # 发布消息
            self.get_logger().info(f"发布了路径文件：{msg.file}")

    def gather_publisher_timer_callback(self):
        global gather
        global post_file_name
        if gather != -1:
            msg = GATHER()  # 构造消息
            if gather == 1:
                timestamp = int(time.time() * 1000)
                print(timestamp)
                post_file_name = f"common/txt/gps_load_{timestamp}.txt"
                msg.file = post_file_name
            msg.gather = gather
            self.gather_publisher_.publish(msg)  # 发布消息
            self.get_logger().info(
                f"发布了采集命令：{msg.gather},文件名:{post_file_name}"
            )
            if gather == 0:
                url = "http://36.153.162.171:9500/api/ccp-service/route/upload"
                # url = "http://192.168.4.117:9500/api/ccp-service/route/upload"
                files = {"file": open(post_file_name, "rb")}
                file_md5 = md5_file(post_file_name)
                data = {"md5": {file_md5}, "vid": "V020001"}
                response = requests.post(url, params=data, files=files)
                print(response.text)
            gather = -1


def init_main():
    print("init")


def main(args=None):
    init_main()
    new_job = threading.Thread(target=run, name="Add1", args=())
    # 设置为守护线程
    new_job.setDaemon(True)
    new_job.start()

    rclpy.init(args=args)  # 初始化rclpy
    node = RouteNode("RouteNode")  # 新建一个节点
    rclpy.spin(node)  # 保持节点运行，检测是否收到退出指令（Ctrl+C）
    rclpy.shutdown()  # 关闭rclpy
