from django.http import HttpResponse

from rest_framework.views import APIView

from api.models import Graph , User
from api.utils import *

class GraphicSelectAPI(APIView):
    def get(self , request):
        user = request.user
        print(user)
        graphics = []
        if(user.identity == 'admin'):
            graphiclist = Graph.objects.all()
            print(graphiclist)
            for graph in graphiclist:
                graphics.append({
                    "id": graph.id,
                    "nodes": graph.nodes,
                    "type": graph.type,
                    "edges": graph.edges,
                    "createTime": graph.create_time,
                    "updateTime": graph.update_time,
                    "resultId": graph.result_id,
                    "userId": graph.user_id 
                })
        else:
            graphiclist = Graph.objects.filter(user_id = user.id)
            for graph in graphiclist:
                graphics.append({
                    "id": graph.id,
                    "nodes": graph.nodes,
                    "type": graph.type,
                    "edges": graph.edges,
                    "createTime": graph.create_time,
                    "updateTime": graph.update_time,
                    "resultId": graph.result_id,
                    "userId": graph.user_id 
                })
        return success(message = "图形数据查询成功" , 
                        data = graphics , code = 200)
    

class GraphicDownloadAPI(APIView):
    def post(self, request):
        try:
            print(request.data)
            graph = Graph.objects.get(id = request.data.get("id"))
            print(graph)
        except Graph.DoesNotExist:
            return failed(message = "文件不存在", status=404)

        # 创建CSV响应
        response = HttpResponse(content_type='text/csv')
        response['Content-Disposition'] = f'attachment; filename="{graph.name}.csv"'
        
        # 写入CSV内容，假设file.content是CSV格式的字符串
        response.write(graph.nodes)
        
        return success(message = "图形数据下载成功" , 
                        data = response , code = 200)

