from rest_framework.views import APIView
from rest_framework import generics, status
from rest_framework.response import Response
from googleapiclient.http import MediaIoBaseUpload
from io import BytesIO
from core.settings import DRIVE_SERVICE, EVENTBOOKINGS_FOLDER_CONTENT_ID, PROFILEPICTURES_FOLDER_CONTENT_ID
from authentication.firebase_auth import FirebaseAuthentication
from events.models import Booking, Event, UserBooking


class FileUploadAPIView(APIView):
    authentication_classes = [FirebaseAuthentication]

    def post(self, request, *args, **kwargs):
        try:
            DOCTYPES = ["chat", "profilepicture", "paymentslip"]
            if not request.data.get("docType") or request.data.get("docType") not in DOCTYPES:
                return Response({'detail': "docType field is missing or invalid"}, status=status.HTTP_404_NOT_FOUND)

            if request.data.get("docType") == "paymentslip":
                if not request.data.get("booking"):
                    return Response({'detail': "booking identifier is required"}, status=status.HTTP_404_NOT_FOUND)

                # VALIDATING BOOKING
                booking_instance = Booking.objects.filter(
                    userbooking__userrole__user=request.user, uid=request.data.get("booking")).first()
                if not booking_instance:
                    return Response({'detail': "Booking does not exist"}, status=status.HTTP_404_NOT_FOUND)

                try:
                    res = DRIVE_SERVICE.files().list(
                        q=f"'{booking_instance.drive_folder_id}' in parents and name = 'payments' and mimeType='application/vnd.google-apps.folder'", pageSize=10, fields="files(id, name)").execute()
                except:
                    return Response({'detail': "Please contact the company."}, status=status.HTTP_404_NOT_FOUND)

                payments_folder_content_id = res['files'][0]['id']
                file_ids = []
                for uploaded_file in request.FILES.getlist('files'):
                    file_metadata = {
                        'name': uploaded_file.name,
                        'parents': [payments_folder_content_id]
                    }
                    media = MediaIoBaseUpload(
                        BytesIO(uploaded_file.read()), mimetype=uploaded_file.content_type)
                    file = DRIVE_SERVICE.files().create(
                        body=file_metadata, media_body=media, fields='id').execute()
                    file_ids.append(file.get('id'))

                return Response({'file_ids': file_ids}, status=status.HTTP_201_CREATED)

            if request.data.get("docType") == "chat":
                if not request.data.get("event"):
                    return Response({'detail': "event identifier is required"}, status=status.HTTP_404_NOT_FOUND)

                # VALIDATING EVENT
                event_instance = Event.objects.filter(
                    booking__userbooking__userrole__user=request.user, uid=request.data.get("event")).first()
                if not event_instance:
                    return Response({'detail': "Event does not exist"}, status=status.HTTP_404_NOT_FOUND)

                try:
                    res = DRIVE_SERVICE.files().list(
                        q=f"'{event_instance.drive_folder_id}' in parents and name = 'chats' and mimeType='application/vnd.google-apps.folder'", pageSize=10, fields="files(id, name)").execute()
                except:
                    return Response({'detail': "Please contact the company."}, status=status.HTTP_404_NOT_FOUND)

                chats_content_id = res['files'][0]['id']
                file_ids = []
                for uploaded_file in request.FILES.getlist('files'):
                    file_metadata = {
                        'name': uploaded_file.name,
                        'parents': [chats_content_id]
                    }
                    media = MediaIoBaseUpload(
                        BytesIO(uploaded_file.read()), mimetype=uploaded_file.content_type)
                    file = DRIVE_SERVICE.files().create(
                        body=file_metadata, media_body=media, fields='id').execute()
                    file_ids.append(file.get('id'))

                return Response({'file_ids': file_ids}, status=status.HTTP_201_CREATED)

            elif request.data.get("docType") == "profilepicture":
                file_ids = []
                for uploaded_file in request.FILES.getlist('files'):
                    file_metadata = {
                        'name': f"{request.user.uid}_{uploaded_file.name}",
                        'parents': [PROFILEPICTURES_FOLDER_CONTENT_ID]
                    }
                    media = MediaIoBaseUpload(
                        BytesIO(uploaded_file.read()), mimetype=uploaded_file.content_type)
                    file = DRIVE_SERVICE.files().create(
                        body=file_metadata, media_body=media, fields='id').execute()
                    file_ids.append(file.get('id'))

                return Response({'file_ids': file_ids}, status=status.HTTP_201_CREATED)

            return Response({'detail': "Invalid document type"}, status=status.HTTP_404_NOT_FOUND)
        except Exception as e:
            print(e)
            return Response({'detail': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
