import datetime, os, json, jsonlint

from django.shortcuts import render

from django.views.generic import TemplateView
from django.http import JsonResponse
from django.views import View



from .utils import ( speech_words, excel_to_json_epg, excel_to_json_views,
                     add_show_to_views, add_calcul_to_epg, generate_static_json,
                     get_excel_ads, count_ads_by_brand, get_brands_by_id, get_week_dates,
                     count_ads_by_date, read_json_file
                    )
# Create your views here.

categories_data = [
    {
        "id": "",
        "name": "Select a Categorie"
    },
    {
        "id": "telecommunications",
        "name": "Telecommunications",
        "brands": ["Inwi", "Orange", "Maroc-Telecom"]
    },
    {
        "id": "automotive",
        "name": "Automotive",
        "brands": ["Dacia", "Skoda", "peugeot"]
    },
    # {
    #     "id": "food-and-beverage",
    #     "name": "Food and Beverage",
    #     "brands": ["Danone", "Aicha", "Dari", "Star", "Kayna", "Laprairie", "Asta", "Leader-Chips", "Lesieur", "Kinder",
    #                "Conikos", "Familia", "Lhdya", "Jaouda", "Excelo", "Sidi-Ali", "kenz", "Be-Biscuits", "delicia","samar",
    #                "solis", "nutella", "mzya", "frout", "tayba", "dalya", "Tobigo", "alitkan", "noody", "Lilia", "Nescafe"]
    # },
    {
        "id": "food-and-beverage",
        "name": "Food and Beverage",
        "brands": ["Aicha", "Dari", "Star", "Kayna", "La prairie", "Asta", "Leader_Chips", "Lesieur", "Kinder", "Conikos"]
    },
    {
        "id": "travel",
        "name": "Travel",
        "brands": ["oncef", "ram"]
    },
    {
        "id": "Home",
        "name": "Home",
        "brands": ["richbond", "Lbassma"]
    },
    {
        "id": "health-and-beauty",
        "name": "Health and Beauty",
        "brands": ["Garnier", "oriel", "Mia"]
    },
    {
        "id": "laundry-detergents-and-fabric-care",
        "name": "Laundry detergents and fabric care",
        "brands": ["Arial","Mio"]
    },
    {
        "id": "retail",
        "name": "Retail",
        "brands": ["Carrefour", "Marjane", "Electro-planet", "morocco-mall"]
    },
    {
        "id": "education",
        "name": "Education",
        "brands": ["OFPPT",]
    },
    {
        "id": "government",
        "name": "Government"
    },
    {
        "id": "non-profit",
        "name": "Non-profit",
        "brands": ["NARSA",]
    },
    {
        "id": "gaz",
        "name": "Gaz",
        "brands": ["Tisir-gaz",]
    },
    {
        "id": "finance",
        "name": "Finance",
        "brands": ["cash plus" ,"chaabi" ,"sendwave"]
    },
]

            # Call the excel_to_json & excel_to_json_views functions to generate the JSON object

 
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


class PiracyControlView(TemplateView):
    template_name = "pages/piracy_control.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

def get_categories(request):
    ads_data = get_excel_ads("/var/www/html/Presentation_Mo_V2/src/media/media_planning_14-21_v2.csv")
    updated_categories = []

    for category in categories_data:
        brands = category.get("brands", [])  # Assuming "brands" is the key for brand data

        if category.get("id") == "":
            updated_categories.append(category)

        matching_brands = [brand for brand in brands if any(ad.get("Brand") == brand for ad in ads_data)]

        if matching_brands:
            updated_categories.append(category)

    return JsonResponse(updated_categories, safe=False)

def get_brands(request):
    """
    Returns a list of all brands across all categories.
    """
    all_brands = []

    for category in categories_data:
        if "brands" in category:
            all_brands.extend(category["brands"])

    return JsonResponse({"brands": all_brands})

def get_brands_by_category(request, category_id):
    """
    Returns a list of brands associated with the given category name.
    """
    # Find the category with the given name
    for category in categories_data:
        if category["id"] == category_id and "brands" in category:
            return JsonResponse({"brands": category["brands"]})
    # If no matching category is found, return an empty list
    return JsonResponse({"brands": []})


class MediaPlanningView(View):

    def get (self, request):

        template_name = "pages/media_planning.html"
        context = {}
        return render(request, template_name, context)

    def post(self, request):
        category_id = request.POST.get("category_id")
        brands_list = request.POST.get("brands")
        selected_week = request.POST.get("week")
        selected_day = request.POST.get("day")
        chart_type = request.POST.get("value")
        ads_data = get_excel_ads("/var/www/html/Presentation_Mo_V2/src/media/media_planning_14-21_v2.csv")

        if category_id and chart_type == "comparison_brands_category":
            # print(ads_data)
            brand_str = ",".join(get_brands_by_id(categories_data, category_id)) if brands_list == "" else brands_list
            # Retrieve data for comparison of 3 brands in the same category based on category_id
            # Dummy data for the chart
            chart_data =  count_ads_by_brand(ads_data, brand_str)
            # Retrieve data for comparison of 3 brands in the same category based on category_id
            # Dummy data for the chart
            response = {
                "chart": "PieAdsChart",
                "data": chart_data
            }

        elif selected_week and chart_type == "columns_ads_chart":
            print()

            # Retrieve data for the distribution of a brand"s ads in the selected category based on category_id
            # Dummy data for the chart
            chart_data = [{
                    "name": "Ads Count",
                    "data": count_ads_by_date(ads_data, get_week_dates(selected_week))
                } 
            ]
            response = {
                "chart": "ColumnsAdsChart",
                "data": chart_data
            }
        elif selected_day and chart_type == "spline_ads_chart": 
            import random
            names = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
            # Number of data points
            num_data_points = 24

            # Generate data
            chart_data = []
            for name in names:
                # Generate a list of random data points
                data_points = [random.randint(0, 240) for _ in range(num_data_points)]
                # Create a dictionary with the name and data attributes
                item = {"name": name, "data": data_points}
                # Add the dictionary to the list
                chart_data.append(item)

            response = {
                "chart": "SplineAdsChart",
                "data": chart_data
            }
        else:
            response = {}

        return JsonResponse(response, content_type="application/json")
 
class VideoAnalysisView(View):

    def get(self, request):
        template_name = "pages/video_analysis.html"
        context = {}
        return render(request, template_name, context)

    def post(self, request):
        # Get the uploaded file from the request
        # video_file = request.FILES["video_file"]

        # Analyze the video file
        # Read the contents of the json file
        detected_objects = generate_static_json(
            "/var/www/html/Presentation_Sanoa_Al_oula/src/media/Jt_en_Français_Al_Aoula_du_18_06_2023_2_min_2023_06_19_15_49_04.json",
            "/var/www/html/Presentation_Mo_V2/src/media/Info_Soir_Dimanche_07_Mai_2023_2023_05_08_19_46_02_static.json",
            confidence_value=80
        )

        # Open the file in read mode
        with open("/var/www/html/Presentation_Sanoa_Al_oula/src/media/Jt_en_Français_Al_Aoula_du_18_06_2023_2_min_2023_06_19_15_49_04.txt", "r") as file:
            # Read the contents of the file
            text = file.read()
        obj_speech_words = speech_words(text)
        # Return the analysis results as a JSON response
        analysis_results = {
            "detected_objects": detected_objects,
            "speech_words": obj_speech_words
        }
        return JsonResponse(analysis_results, content_type="application/json")

class CommentsAnalyzerView(View):

    def get (self, request):

        template_name = "pages/comments_analyzer.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

        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

        # 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, "type":"json"}
        # 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": file_contents, "type":"text"}
        #     except jsonlint.ValidationError as e:
        #         print("Validation error:", e)
        #         analysis_results = {"success": False, "error": str(e)}

        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, "type":"json"}
        except json.JSONDecodeError:
            analysis_results = {"success": True, "data": file_contents.replace(",",",\n"), "type":"text"}

        # 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")

class VideoSubtitlesView(View):

    def get(self, request):
        template_name = "pages/video_subtitles.html"
        context = {}
        return render(request, template_name, context)

    def post(self, request):
        pass


class MusicRemovalView(View):

    def get(self, request):
        template_name = "pages/music_removal.html"
        context = {}
        return render(request, template_name, context)

    def post(self, request):
        pass
  

class DynamicAdInsertionView(View):

    def get(self, request):
        template_name = "pages/dynamicAdInsertion.html"
        context = {}
        return render(request, template_name, context)

    def post(self, request):
        pass
 

class ReportView(View):
    template_name = "pages/reports.html"

    def get_reports_dict(self):
        reports_dict = {
            "Aicha - Ep 12": {
                "title": "Aicha - Ep 12 - عايشة الحلقة",
                "video_src": "8AVn-iXYFo0",
                "report": open("/var/www/html/Presentation_Sanoa_Al_oula/src/media/reports/Aicha-Ep12.txt", "r").read(),
                "comments": read_json_file("/var/www/html/Presentation_Sanoa_Al_oula/src/media/reports/Aicha-Ep12.json"),
            },
            "Chef Academy - Prime 1": {
                "title": "Chef Academy - Prime  شاف أكاديمي - برايم 1",
                "video_src": "o3S06MQsStE",
                "report": open("/var/www/html/Presentation_Sanoa_Al_oula/src/media/reports/Chef_Academy_Prime1.txt", "r").read(),
                "comments": read_json_file("/var/www/html/Presentation_Sanoa_Al_oula/src/media/reports/Chef_Academy_Prime1.json"),
            },
        }
        return reports_dict

    def get(self, request, show_name):
        reports_dict = self.get_reports_dict()
        context = {"report": reports_dict.get(show_name, {})}  # Get the report details based on show_name
        return render(request, self.template_name, context)

