// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import Foundation

/// An image format for images generated by Imagen.
///
/// To specify an image format for generated images, set ``ImagenGenerationConfig/imageFormat`` in
/// your ``ImagenGenerationConfig``. See the [Cloud
/// documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/imagen-api#output-options)
/// for more details.
@available(iOS 15.0, macOS 12.0, macCatalyst 15.0, tvOS 15.0, watchOS 8.0, *)
public struct ImagenImageFormat {
  let mimeType: String
  let compressionQuality: Int?

  /// PNG image format.
  ///
  /// Portable Network Graphic (PNG) is a lossless image format, meaning no image data is lost
  /// during compression. Images in PNG format are *typically* larger than JPEG images, though this
  /// depends on the image content and JPEG compression quality.
  public static func png() -> ImagenImageFormat {
    return ImagenImageFormat(mimeType: "image/png", compressionQuality: nil)
  }

  /// JPEG image format.
  ///
  /// Joint Photographic Experts Group (JPEG) is a lossy compression format, meaning some image data
  /// is discarded during compression. Images in JPEG format are *typically* larger than PNG images,
  /// though this depends on the image content and JPEG compression quality.
  ///
  /// - Parameters:
  ///   - compressionQuality: The JPEG quality setting from 0 to 100, where `0` is highest level of
  ///     compression (lowest image quality, smallest file size) and `100` is the lowest level of
  ///     compression (highest image quality, largest file size); defaults to `75`.
  public static func jpeg(compressionQuality: Int? = nil) -> ImagenImageFormat {
    if let compressionQuality, compressionQuality < 0 || compressionQuality > 100 {
      AILog.warning(code: .imagenInvalidJPEGCompressionQuality, """
      Invalid JPEG compression quality of \(compressionQuality) specified; the supported range is \
      [0, 100].
      """)
    }
    return ImagenImageFormat(mimeType: "image/jpeg", compressionQuality: compressionQuality)
  }
}
