#!python
# encoding: utf-8

import click
from ipynbcompress import compress
from hurry.filesize import size, verbose
from tempfile import mkstemp
from shutil import copyfile
from os import close, remove
from sys import exit


@click.command()
@click.argument("filename", type=click.Path(exists=True, dir_okay=False))
@click.argument(
    "output_filename", required=False, type=click.Path(dir_okay=False), default=None
)
@click.option(
    "-w",
    "--img-width",
    type=int,
    default=2048,
    help="Which width images should be resized to.",
)
@click.option(
    "-f",
    "--img-format",
    type=click.Choice(["png", "jpeg"]),
    default="png",
    help="Which compression to use on the images, valid options are png or jpeg (required libjpeg).",
)
def main(filename, output_filename, img_width, img_format):
    """Compress images in IPython notebooks.

    Process the notebook FILENAME into OUTPUT_FILENAME. If an output name is not given
    the file is processed in place.
    """
    if img_format == "jpg":
        img_format = "jpeg"
    if img_format not in ("jpeg", "png"):
        print("ipynb-compress: error: format %s unknown" % img_format)
        print("valid options are png and jpeg")
        exit(1)

    try:
        # write to temp file in case compression fails
        temp_fd, temp_filename = mkstemp(".ipynb")
        close(temp_fd)

        saved = compress(filename, temp_filename, img_width, img_format)

        if output_filename:
            from_to = "%s->%s" % (filename, output_filename)
        else:
            from_to = filename
            output_filename = filename

        if saved > 100000:
            copyfile(temp_filename, output_filename)
            saved = size(saved, system=verbose)
            print("%s: %s decrease" % (from_to, saved))
        else:
            if filename == output_filename:
                print(
                    "%s: compression less than 100k bytes - keeping original" % from_to
                )
            else:
                print(
                    "%s: compression less than 100k bytes - copying original" % from_to
                )
                copyfile(filename, output_filename)

        remove(temp_filename)

    except FileNotFoundError:
        print("ipynb-compress: error: %s file not found" % filename)


if __name__ == "__main__":
    main()
