from rest_framework import serializers
from .models import ProductSample,EndUser,UserActivity,Shoots,InReviewProductData,AddCollectionProduct,CollectionsProduct
import requests
from urllib.parse import urlparse
import dropbox
import logging
from dropbox.files import SharedLink  # ✅ Correct import!


logger = logging.getLogger(__name__)



APP_KEY = 's4sb9uwrs421idv'
APP_SECRET = 'qwlwv2hqhupsbba'
REFRESH_TOKEN = 'B-Crg4k7lAIAAAAAAAAAAfEvWo-ra7xjYP6ZGJDErSpM4-6Qy1b81ryYBQVBKxuG'

dbx = dropbox.Dropbox(
    oauth2_refresh_token=REFRESH_TOKEN,
    app_key=APP_KEY,
    app_secret=APP_SECRET
)

class EndUserSerializer(serializers.ModelSerializer):
    class Meta:
        model = EndUser
        fields = '__all__'
        
        
class UserActivitySerializer(serializers.ModelSerializer):
    class Meta:
        model = UserActivity
        fields = '__all__'
        
  
class InReviewProductDataSerializer(serializers.ModelSerializer):
    client_email = serializers.EmailField(source='client.email', read_only=True)

    class Meta:
        model = InReviewProductData
        fields = ["id",'client_email', 'assign_date','is_viewed', 'start_date', 'end_date']      
        
class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = EndUser
        fields = ['id', 'first_name', 'last_name', 'email']  # Add any other fields you need

class ShootsSerializer(serializers.ModelSerializer):
    user = UserSerializer()

    class Meta:
        model = Shoots
        fields = ['user', 'start_date', 'end_date','is_watcher']
        
class ProductSampleSerializer(serializers.ModelSerializer):
    assigned_clients = serializers.SerializerMethodField()
    collection_names = serializers.SerializerMethodField()

    class Meta:
        model = ProductSample
        fields = '__all__'  # or explicitly list fields + 'assigned_clients' + 'collection_names'

    def get_assigned_clients(self, obj):
        review_data = InReviewProductData.objects.filter(product=obj)
        return InReviewProductDataSerializer(review_data, many=True).data
    
    def get_collection_names(self, obj):
        """Get all collection names that this product belongs to"""
        collection_products = AddCollectionProduct.objects.filter(product=obj).select_related('collection')
        collection_names = [cp.collection.collection_name for cp in collection_products if cp.collection]
        return collection_names       
        
class ProductSampleSerializerClient(serializers.ModelSerializer):

    class Meta:
        model = ProductSample
        fields = '__all__' 
        
        
# class ProductSampleSerializer(serializers.ModelSerializer):
#     shoots = serializers.SerializerMethodField()
#     dropbox_thumbnail = serializers.SerializerMethodField()

#     class Meta:
#         model = ProductSample
#         fields = '__all__'  # This includes all sample fields plus "shoots"
#         extra_fields = ['shoots', 'dropbox_thumbnail']
        
#     def get_shoots(self, obj):
#         shoots = Shoots.objects.filter(product=obj)
#         if shoots.exists():
#             shoot_data = []
#             for shoot_obj in shoots:
#                 shoot_data.append({
#                     "user": {
#                         "id": shoot_obj.user.id if shoot_obj.user else None,
#                         "first_name": shoot_obj.user.name if shoot_obj.user else None,
#                         "email": shoot_obj.user.email if shoot_obj.user else None,
#                         "image": shoot_obj.user.image if shoot_obj.user else None,
#                         "is_watcher":shoot_obj.is_watcher,
#                     },

#                 })
#             return shoot_data
#         return []
    
#     def get_dropbox_thumbnail(self, obj):
#         dropbox_url = obj.dropbox_url
#         if not dropbox_url:
#             logger.error("No Dropbox URL provided.")
#             return None

#         try:
#             logger.info(f"Processing Dropbox URL: {dropbox_url}")

#             # ✅ Correct: create SharedLink object
#             shared_link_obj = SharedLink(url=dropbox_url)

#             # List files inside the shared folder
#             res = dbx.files_list_folder(path="", shared_link=shared_link_obj)
#             logger.info(f"Files fetched: {len(res.entries)}")

#             # Find first image
#             for entry in res.entries:
#                 if isinstance(entry, dropbox.files.FileMetadata):
#                     if entry.name.lower().endswith(('.jpg', '.jpeg', '.png', '.webp')):
#                         temp_link = dbx.files_get_temporary_link(entry.path_display)
#                         logger.info(f"Found image: {entry.name}")
#                         return temp_link.link

#             logger.warning("No image found in the Dropbox folder.")
#             return None

#         except Exception as e:
#             logger.error(f"Error fetching thumbnail: {str(e)}")
#             return None