#!/usr/bin/python
from PIL import Image
import sys


def main():
    argn = len(sys.argv)
    if argn == 1:
        print_error("You must specify an input file")
        exit(1)
    elif argn == 2:
        print_error("You must specify an output file")
        exit(1)

    input_image_path = sys.argv[1]
    output_image_path = sys.argv[2]

    try:
        image = Image.open(input_image_path)
    except IOError:
        print_error(f"Cannot open image file {input_image_path}")
        image.close()
        exit(1)

    width, height = image.size
    target_width = int(max(width/2, 1280))
    new_height = int(target_width * height / width)

    image = image.resize((target_width, new_height), Image.Resampling.BICUBIC)
    image = rotate_image(image)

    kwargs = {"quality": 50}
    if "exif" in image.info.keys():
        kwargs["exif"] = image.info["exif"]

    try:
        image.save(output_image_path, **kwargs)
    except IOError:
        print_error(f"Cannot save file {output_image_path}")
        image.close()
        exit(1)


def print_error(string):
    print(f"resize-img Error: {string}")


def rotate_image(image):
    exif = image.getexif()
    if exif is None:
        return image

    orientation = exif.get(0x0012, 1)  # 0x0112 is the EXIF code for orientation
    if orientation == 1:
        return image
    elif orientation == 3:
        image = image.rotate(180, expand=True)
    elif orientation == 6:
        image = image.rotate(270, expand=True)
    elif orientation == 8:
        image = image.rotate(90, expand=True)
    return image


if __name__ == "__main__":
    main()
