import json
import uuid
import os
import time


from django.http import JsonResponse, Http404, HttpResponse
from utils import connect_virtual
from utils import change_state1

# Create your views here.


def virtual_ip(request):
    try:
        # 假设这个函数从数据库或其他地方获取虚拟 IP 信息
        ip_info = connect_virtual.main()
        return HttpResponse(ip_info, content_type='text/plain')
    except Exception as e:
        # 如果发生错误，返回 HTTP 500 服务器错误响应
        return HttpResponse(str(e), status=500, content_type='text/plain')
def change_state(request):
    if request.method == 'POST':
        flag= connect_virtual.state()
        if flag == 1:
            change_state1.change1()
        if flag == 0:
            change_state1.change2()
        return JsonResponse({'key': 'value'})
    else:
        # 如果不是 POST 请求，返回错误或其它响应
        return JsonResponse({'error': 'Invalid request'}, status=400)

def change_state_actively(request):
    if request.method == 'POST':
        # 获取 JSON 数据
        nodes_data = json.loads(request.body)

        flag=connect_virtual.node_state(nodes_data)
        if flag == 1:
            change_state1.change1()
        if flag == 0:
            change_state1.change2()
        # 处理数据，例如保存到数据库或进行逻辑处理
        # ...
        print(nodes_data)
        # 返回响应
        return JsonResponse({'status': 'success', 'data': 'Your processed data'})
    else:
        return JsonResponse({'status': 'error', 'message': 'Only POST method allowed'}, status=405)