# tasks.py

from django.core.exceptions import ObjectDoesNotExist

from ..models.image_gallery import ImageGallery


# @shared_task
def generate_image(image_id, size):
    '''
    image=>ImageGallery.objects
    size==>ImageGallery.ImageSizePreset
    '''
    try:
        validate_size_preset(size)
        image = ImageGallery.objects.get(pk=image_id)
        from PIL import Image as PILImage
        with image.image.open() as f:
            
            img = PILImage.open(f).convert('RGB')  # 格式兼容
            width, height = image.get_size_params(size)
            target_path = image.processed_upload_to(size)

            if width:
                img.thumbnail((width, height or 99999))
                img.save(target_path, optimize=True, quality=85)  # 压缩优化
            else:
                img.save(target_path)

    except ObjectDoesNotExist:
        print(f"Image {image_id} not found.")
    except Exception as e:
        print(f"Error processing image: {str(e)}")


def validate_size_preset(size_preset):
    """确保传入的尺寸预设有效"""
    valid_presets = ImageGallery.ImageSizePreset.values
    if size_preset not in valid_presets:
        raise ValueError(
            f"Invalid size preset. Valid options: {valid_presets}")
