import os
import socket
import time

time.sleep(20)

def get_local_ip():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(("8.8.8.8", 80))
        ip = s.getsockname()[0]
        s.close()
        return ip
    except Exception as e:
        print(f"获取本地IP地址时出错: {e}")
        return None


def write_to_file(data):
    try:
        # 打开文件，模式为写入模式（会清空已有内容）
        with open("/home/orangepi/car/master/Deviceld.txt", "w", encoding="utf-8") as file:
            file.write(data)
        print("数据已成功写入 Deviceld.txt")
    except Exception as e:
        print(f"写入文件时出错: {e}")


def read_from_file():
    try:
        if os.path.exists("/home/orangepi/car/master/Deviceld.txt"):
            with open("/home/orangepi/car/master/Deviceld.txt", "r", encoding="utf-8") as file:
                return file.read()
        return "文件内容为空。"
    except Exception as e:
        print(f"读取文件时出错: {e}")
        return "无法读取文件内容。"


if __name__ == '__main__':
    local_ip = get_local_ip()
    if local_ip is None:
        print("无法获取本地IP地址，程序退出。")
    else:
        server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        server_address = (local_ip, 8080)
        server_socket.bind(server_address)
        server_socket.listen(5)

        print(f'Server is running on http://{server_address[0]}:{server_address[1]}')

        while True:
            client_socket, client_address = server_socket.accept()
            print(f'Accepted connection from {client_address[0]}:{client_address[1]}')

            try:
                request_data = client_socket.recv(1024).decode('utf-8')
                if not request_data:
                    continue

                request_lines = request_data.split('\n')
                request_line = request_lines[0]
                method, path, _ = request_line.split(' ')
                print(f'Received {method} request for {path}')

                if method == "POST" and path == "/submit":
                    # 从请求体中提取数据
                    body = request_lines[-1]  # 请求体在最后一行
                    data = body.split('=')[1] if '=' in body else body

                    # 保存数据到文件
                    write_to_file(data)

                     # 返回确认响应
                    response_body = f"""
                    <html>
                        <head><title>数据提交成功</title></head>
                        <body>
                            <h1>数据已成功提交！</h1>
                            <a href="/">返回主页</a>
                        </body>
                    </html>
                    """
                    status_code = '200 OK'

                elif method == "GET" and path == "/":
                    # 读取文件内容
                    file_content = read_from_file()

                    # 返回 HTML 页面
                    response_body = f'''
                        <html>
                            <head>
                                <title>设备输入页面</title>
                                <style>
                                    body {{ font-family: Arial, sans-serif; background-color: #f4f4f9; margin: 0; padding: 0; }}
                                    .container {{ max-width: 600px; margin: 50px auto; padding: 20px; 
                                                background: white; border-radius: 8px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); }}
                                    h1 {{ text-align: center; }}
                                    textarea {{ width: 100%; height: 150px; margin: 10px 0; 
                                                padding: 10px; border: 1px solid #ccc; border-radius: 4px; resize: none; }}
                                    form {{ margin-top: 20px; }}
                                    input[type="text"] {{ width: 90%; padding: 10px; 
                                                        margin: 10px 0; border: 1px solid #ccc; border-radius: 4px; font-size: 16px; }}
                                    input[type="submit"] {{ background: #007bff; color: white; 
                                                        padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; }}
                                    input[type="submit"]:hover {{ background: #0056b3; }}
                                </style>
                            </head>
                            <body>
                                <div class="container">
                                    <h1>欢迎进入设备管理界面！</h1>
                                    <textarea readonly>{file_content}</textarea>
                                    <form action="/submit" method="post">
                                        <input type="text" name="data" placeholder="请输入一些数据" required>
                                        <input type="submit" value="提交">
                                    </form>
                                </div>
                            </body>
                        </html>
                    '''
                    status_code = '200 OK'

                else:
                    response_body = '<h1>404 Not Found</h1>'
                    status_code = '404 Not Found'

                response_headers = (
                    f'HTTP/1.1 {status_code}\n'
                    f'Content-Type: text/html; charset=utf-8\n'
                    f'Content-Length: {len(response_body.encode("utf-8"))}\n'
                    f'Connection: close\n\n'
                )

                response = response_headers + response_body
                client_socket.sendall(response.encode('utf-8'))

            except Exception as e:
                print(f'Error handling request: {e}')
                error_response = (
                    'HTTP/1.1 500 Internal Server Error\n'
                    'Content-Type: text/html; charset=utf-8\n'
                    'Connection: close\n\n'
                    '<h1>500 内部服务器错误</h1>'
                )
                client_socket.sendall(error_response.encode('utf-8'))
            finally:
                client_socket.close()
