from django.shortcuts import render
from rest_framework.response import Response
from rest_framework import generics, status
from django.http import JsonResponse
import json
import requests
from django.db.models import Count
from rest_framework.permissions import IsAuthenticated
from .models import Product, Rekomendasi
from recipes.models import Information, Ingredient, Unit, RawIngredient, Tag
from profiles.models import Pantry
from django.db.models import Q, Subquery, OuterRef, Func, F, Count
from .serializers import ProductSerializer

# Create your views here.


class ProductView(generics.GenericAPIView):
    def post(self, request):
        Product.objects.all().delete()
        panenpanen_data = requests.get(
            'http://127.0.0.1:8080/api/v1/easycook/products')
        json_data = panenpanen_data.json()
        products = json_data.get('data', [])
        for product in products:
            id_product = product.get('id')
            nama_bahan = product.get('nama_bahan')
            harga = product.get('harga')
            berat = product.get('berat')
            satuan = product.get('satuan')
            nama_supplier = product.get('nama_supplier')
            alamat = product.get('alamat-supplier')
            data = Product(id_product=id_product, nama_bahan=nama_bahan, harga=harga,
                           berat=berat, satuan=satuan, nama_supplier=nama_supplier, alamat=alamat)
#            data.save()

        response_data = {
            'data': 'Data berhasil disimpan',
            'status': 'success',
        }
        return JsonResponse(response_data)


class RekomendasiView(generics.GenericAPIView):
    serializer_class = ProductSerializer

    def get_queryset(self):
        return Information.objects.filter(pk=self.kwargs['id']).prefetch_related('ingredient_set')

    def get(self, request, id):
        user = request.user
        Rekomendasi.objects.filter(user_id=user.id).delete()
        # Product.objects.all().delete()
        recipe = Information.objects.filter(pk=self.kwargs['id'])
        recipe_id = recipe.get().id

        # panenpanen_data = requests.get(
        #     'http://152.69.206.130:80/api/v1/easycook/products')
        # json_data = panenpanen_data.json()
        # products = json_data.get('data', [])
        # for product in products:
        #     id_product = product.get('id')
        #     nama_bahan = product.get('nama_bahan')
        #     harga = product.get('harga')
        #     berat = product.get('berat')
        #     satuan = product.get('satuan')
        #     nama_supplier = product.get('nama_supplier')
        #     alamat = product.get('alamat-supplier')
        #     data = Product(id_product=id_product, nama_bahan=nama_bahan, harga=harga,
        #                    berat=berat, satuan=satuan, nama_supplier=nama_supplier, alamat=alamat)
        #     data.save()

        owned_raw_materials = Pantry.objects.filter(
            user=request.user).values_list('raw_ingredient', flat=True)

        owned_raw_ingredient_ids = Pantry.objects.filter(
            user=user).values_list('raw_ingredient_id', flat=True)
        not_owned_ingredients = Ingredient.objects.filter(
            recipe_id=recipe_id).exclude(raw_ingredient__in=owned_raw_ingredient_ids)

        for bahan in not_owned_ingredients:
            nama_bahan = bahan.name
            products = Product.objects.filter(
                nama_bahan__icontains=nama_bahan)
            for product in products:
                rekomendasi = Rekomendasi(
                    product_id=product.id, user_id=user.id, supplier=product.nama_supplier)
                rekomendasi.save()

        rangking = Rekomendasi.objects.values('supplier').annotate(
            count=Count('supplier')).order_by('-count')
        data = Rekomendasi.objects.filter(user_id=user.id)
        datas = list(data.values())

        supplier_data = {}
        rekomendasi_bahan = []
        for data in datas:
            product = Product.objects.get(id=data['product_id'])
            supplier = data['supplier']
            if supplier not in supplier_data:
                supplier_data[supplier] = []
            supplier_data[supplier].append({
                'nama_bahan': product.nama_bahan,
                'harga': product.harga,
                'satuan': product.satuan,
                'alamat': product.alamat,
                'berat': product.berat,
                'id_product': product.id_product,
                'nama_supplier': product.nama_supplier,

            })

        rangking_list = []
        for rank in rangking:
            supplier = rank['supplier']
            count = rank['count']
            products = supplier_data.get(supplier, [])
            rangking_list.append({
                'nama_supplier': supplier,
                'jumlah_kesesuaian_bahan': count,
                'produk': products
            })

        return JsonResponse(rangking_list, safe=False)


class RecipeRecomendationView(generics.GenericAPIView):
    def get_owned_ingredients(self, user):
        pantry_items = Pantry.objects.filter(
            user=user).values_list('raw_material_id', flat=True)
        owned_ingredients = IngredientTag.objects.filter(
            raw_material_id__in=pantry_items).values_list('ingredient_id', flat=True).distinct()
        return list(owned_ingredients)

    def get_recipes_with_completeness_percentage(self, request):
        user_count_subquery = IngredientTag.objects.filter(ingredient__recipe_id=OuterRef(
            'pk'), raw_material__pantry__user_id=request.user.id).annotate(count=Func(F("raw_material__pantry__id"), function="Count")).values("count")
        recipes = Information.objects.annotate(completeness_percentage=Subquery(
            user_count_subquery) / Count('ingredient') * 100,)
        return recipes

    def get(self, request):
        user = request.user
        raw_meterials = RawMaterial.objects.all()
        pantry_raw_materials = Pantry.objects.filter(
            user=user).values_list('raw_material_id', flat=True)
        owned_ingredients = self.get_owned_ingredients(user)
        recipes = self.get_recipes_with_completeness_percentage(request).filter(
            ingredient__pk__in=owned_ingredients).order_by('-completeness_percentage').distinct()

        recipe_data = list(recipes.values())

        return JsonResponse({"Rekomendasi resep": recipe_data}, safe=False)
