from django.shortcuts import render
from django.views.generic import TemplateView
from django.http import JsonResponse
from django.views import View
import sys
import os
import openai
import subprocess

import json
# Create your views here.

class DashboardView(TemplateView):
    template_name = 'pages/index.html'

    def get_context_data(self, **kwargs):
        # Get the data for the dashboard.
        data = {}

        # Add the data to the context.
        context = super().get_context_data(**kwargs)
        context['data'] = data
        return context


import jsonlint


class CommentsAnalyzerView(View):

    def get (self, request):

        template_name = 'pages/index.html'
        context = {}
        return render(request, template_name, context)

    def post(self, request):
        # Get the analysis results from the request data
        url = request.POST.get('results')

        # Validate the YouTube video URL and retrieve the comments
        # You can implement this using the YouTube API

        # For the example, we'll use dummy data
        comments = [
            "This is a great video!",
            "I learned a lot from this video.",
            "The presenter is very engaging.",
        ]
        print("python3_start")

        os.system("python3 /var/www/html/exportcomments/youtube_export.py "+url)
        print("python3_end")
        # Process the comments and generate the analysis results
        # You can implement this using your existing analysis code

        # For the example, we'll use dummy analysis results
        analysis_results = {
            'sentiment': 'Positive',
            'keywords': ['video', 'learned', 'engaging']
        }

        # with open('/var/www/html/exportcomments/temp2.json', 'r') as f:
        #     analysis_results = json.load(f)
        #     try:
        #         json_data = json.load(f)
        #         # If the JSON data is in the correct format, process it here
        #         analysis_results = {'success': True, 'data': json_data}
        #     except json.JSONDecodeError:
        #         # If the JSON data is not in the correct format, read the file contents as text instead
        #         f.seek(0)  # Reset the file pointer to the beginning of the file
        #         file_contents = f.read()
        #         # Call jsonlint as a subprocess to fix the formatting errors
        #         fixed_json_data = subprocess.check_output(['jsonlint', '-c'], input=file_contents, universal_newlines=True)
        #         analysis_results = json.loads(fixed_json_data)

        with open('/var/www/html/exportcomments/temp2.json', 'r') as f:
            file_contents = f.read()

            try:
                json_data = json.loads(file_contents)
                # If the JSON data is in the correct format, process it here
                analysis_results = {'success': True, 'data': json_data}
            except json.JSONDecodeError:
                # If the JSON data is not in the correct format, try to fix the formatting errors using jsonlint
                try:

                    analysis_results = {'success': True, 'data': ""}
                except jsonlint.ValidationError as e:
                    print("Validation error:", e)
                    analysis_results = {'success': False, 'error': str(e)}


        # Return the analysis results as a JSON response
        # return JsonResponse(analysis_results, content_type='application/json')
        return JsonResponse(analysis_results, safe=False)
        # return JsonResponse(analysis_results, content_type='document/text')
