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

epg_data = excel_to_json_epg(
    filepath="/var/www/html/Presentation_Mo_V2/src/media/2mepg_2.xlsx",
    sheet_name="diffusions_2023_05_15"
)
views_data = excel_to_json_views("/var/www/html/Presentation_Mo_V2/src/media/extracted_data.xlsx")

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

class VideoAdvertisingView(TemplateView):
    template_name = "pages/video_advertising.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))
                }
                # , {
                #     "name": "Brand B",
                #     "data": [8, 12, 15, 10, 14, 16, 12]
                # }, {
                #     "name": "Brand C",
                #     "data": [5, 10, 8, 12, 16, 18, 15]
                # }
            ]
            response = {
                "chart": "ColumnsAdsChart",
                "data": chart_data
            }
        elif selected_day and chart_type == "spline_ads_chart":
            # 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": "Lun",
            #         "data": [12, 10, 8, 5, 6, 8, 10, 14, 20, 22, 23, 25, 30, 32, 28, 26, 24, 20, 18, 16, 14, 12, 10, 8]
            #     }, {
            #         "name": "Brand B",
            #         "data": [5, 4, 3, 2, 3, 4, 5, 6, 8, 10, 12, 14, 18, 20, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4]
            #     }, {
            #         "name": "Brand C",
            #         "data": [3, 4, 5, 4, 5, 6, 8, 10, 12, 14, 16, 18, 20, 22, 20, 18, 16, 14, 12, 10, 8, 6, 4, 3]
            #     }
            # ]
            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 StatsAndEPGView(View):

    def get (self, request):

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

    def post(self, request):

        date = request.POST.get("date")
        if date :
            # Fetch viewership data and EPG data from the database for the selected date
            date_obj = datetime.datetime.strptime(date, "%Y-%m-%d").date()
            print(date)

            # Filter the data based on the date
            filtered_epg_data = [datum for datum in epg_data if datetime.datetime.strptime(datum["date"], "%Y-%m-%d").date() == date_obj]
            filtered_views_data = [datum for datum in views_data if datetime.datetime.strptime(datum["date"], "%Y-%m-%d").date() == date_obj]
            filtered_views_data = add_show_to_views(filtered_views_data, filtered_epg_data)
            filtered_epg_data = add_calcul_to_epg(filtered_views_data, filtered_epg_data)
            # Create a dictionary containing the data
            data = {
                "viewership_data": filtered_views_data,
                "epg_data": filtered_epg_data
            }
            print(data)
            # Return the data as a JSON response
            return JsonResponse(data, content_type="application/json")
        return JsonResponse({}, 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_Mo_V2/src/media/Info_Soir_Dimanche_07_Mai_2023_2023_05_08_19_46_02.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_Mo_V2/src/media/Info_Soir_Dimanche_07_Mai_2023_v2.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 AdvertisersView(View):

    def get(self, request):
        template_name = "pages/advertisers.html"
        context = {
            "brands": [
                {
                    "brand_name": "Panzani - Zakia",
                    "brand_img": "advertisers/Panzani-Zakia/2.png"
                },

                {
                    "brand_name": "Isla Delice",
                    "brand_img": "advertisers/Isla_Delice/4.png"
                },
                {
                    "brand_name": "Western Union",
                    "brand_img": "advertisers/Western_Union/3.png"
                },
                {
                    "brand_name": "Wafacash",
                    "brand_img": "advertisers/wafacash/wafacash.png"
                }
                # Add more brands as needed
            ]
        }
        return render(request, template_name, context)

class AdvertiserView(View):
    def get(self, request, brand_name):
        template_name = "pages/advertiser.html"
        brand_videos = {
            "Panzani - Zakia": [
                {"title": "Panzani Zakia Spot Ad", "video_src": "advertisers/Panzani-Zakia/panzani_zakia_Spot_Video_1.mp4"},
            ],

            "Isla Delice": [
                {"title": "Isla Delice Spot Ad", "video_src": "advertisers/Isla_Delice/Isla_Delice_1.mp4"},
            ],
            "Western Union": [
                {"title": "Western Union English Spot Ad", "video_src": "advertisers/Western_Union/wu_ad_english_1.mp4"},
                {"title": "Western Union French Spot Ad", "video_src": "advertisers/Western_Union/wu_ad_french_1.mp4"},
            ],
            "Wafacash": [
                {"title": "wafacash Spot Ad", "video_src": "advertisers/wafacash/WAFACASH_Arab_1.mp4"},
            ],
            "Fillers": [
                {"title": "Filler 1", "video_src": "advertisers/Fillers/Filler_1_omnt.mp4"},
                {"title": "Filler 2", "video_src": "advertisers/Fillers/Filler_2_omnt.mp4"},
                {"title": "Filler 3", "video_src": "advertisers/Fillers/Filler_3_omnt.mp4"},
                ],
            # Add more brands and videos as needed
        }

        brand_videos_for_display = brand_videos.get(brand_name, [])

        context = {
            "brand_name": brand_name,
            "brand_videos": brand_videos_for_display,
        }
        return render(request, template_name, context)

class AdvertisingInterfaceView(TemplateView):
    template_name = "pages/interface.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 ReportView(View):
    template_name = "pages/reports.html"

    def get_reports_dict(self):
        reports_dict = {
            "El Mektoub - S2 Ep16": {
                "title": "El Mektoub - S2 Ep16",
                "video_src": "k2NmnIF3hGU",
                "report": open("/var/www/html/Presentation_Mo_V2/src/media/reports/report_Al _Maktoub_S2-E16.txt", "r").read(),
                "comments": open("/var/www/html/Presentation_Mo_V2/src/media/reports/comments_Al _Maktoub_S2-E16.json", "r").read(),
            },
            "El Mektoub - S2 Ep30 Last": {
                "title": "El Mektoub - S2 Ep30 Last",
                "video_src": "iAeuBV0eN7c",
                "report": open("/var/www/html/Presentation_Mo_V2/src/media/reports/report_Al _Maktoub_S2-E30.txt", "r").read(),
                "comments": open("/var/www/html/Presentation_Mo_V2/src/media/reports/comments_Al _Maktoub_S2-E30.json", "r").read(),
            },
        }
        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)

