import base64
import mimetypes
import os
import tempfile
from datetime import datetime

from django.conf import settings
import boto3
from botocore.client import Config
from django.core.exceptions import BadRequest
from django.core.files.base import ContentFile
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

# from common.utils.owncloud_utls import Owncloud
from containers.models import ContainerPhotos, Container
from common.utils.minio_utils import get_damages, upload_damage_photo


class Damages(APIView):
    def post(self, request, depot_id):
        photo = request.data.get("photo")
        extension = request.data.get("photo_extension")

        try:
            # Decode base64 and create a ContentFile
            photo_data = base64.b64decode(photo.encode("utf-8"))

            # Generate a unique filename with proper folder structure
            import uuid
            filename = f"{depot_id}/{datetime.today().strftime('%Y%m%d')}_{uuid.uuid4()}.{extension}"
            photo_file = ContentFile(photo_data, name=filename)

            # Set content type based on file extension
            content_type = mimetypes.guess_type(filename)[0] or 'application/octet-stream'

            # Upload to MinIO and get URL
            url = upload_damage_photo(photo_file, depot_id, content_type)

            # Save to database
            container_photo = ContainerPhotos.objects.create(
                container=Container.objects.get(pk=depot_id),
                photo=url,
                uploaded_by=request.user
            )

            return Response(status=status.HTTP_201_CREATED)

        except Exception as ex:
            print(f"Error in damage photo upload: {str(ex)}")
            return Response(
                {"error": "Failed to process photo"},
                status=status.HTTP_400_BAD_REQUEST
            )

    def get(self, request, depot_id):
        try:
            s3_client = boto3.client('s3',
                                     endpoint_url=f"http://{settings.MINIO_ENDPOINT}",
                                     aws_access_key_id=settings.MINIO_ACCESS_KEY,
                                     aws_secret_access_key=settings.MINIO_SECRET_KEY,
                                     config=Config(signature_version='s3v4')
                                     )

            prefix = f"{depot_id}/"
            response = s3_client.list_objects_v2(
                Bucket=settings.MINIO_BUCKET_NAME,
                Prefix=prefix
            )

            photos = []
            if 'Contents' in response:
                for obj in response['Contents']:
                    url = f"{settings.MINIO_SERVER_URL}/{settings.MINIO_BUCKET_NAME}/{obj['Key']}"
                    photos.append({'url': url})

            return Response(photos, status=status.HTTP_200_OK)

        except Exception as e:
            print(f"MinIO Error: {str(e)}")
            return Response(
                {"error": "Failed to retrieve photos"},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR
            )