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

 
views_data = excel_to_json_views("/var/www/html/Presentation_Sanoa_Al_oula_2024/src/media/AlOula_France_SFR_1.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 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() 

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


        # Return the analysis results as a JSON response
        analysis_results = {
            "detected_objects": detected_objects
        }
        return JsonResponse(analysis_results, content_type="application/json")

class VideoAnalysisNewsView(View):

    def get(self, request):
        template_name = "pages/video_analysis_news.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_2024/src/media/JT_segment_04012024_2024_01_08_10_10_37.json",
            "/var/www/html/Presentation_Sanoa_Al_oula_2024/src/media/JT_segment_04012024_2024_01_08_10_10_37.json",
            confidence_value=80
        )


        # Return the analysis results as a JSON response
        analysis_results = {
            "detected_objects": detected_objects
        }
        return JsonResponse(analysis_results, content_type="application/json")
    
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 AdtlasPresentationView(View):

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

    def post(self, request):
        pass
 