#!/usr/bin/env python
"""TinyPNG API

Python module and command line tool for api.tinypng.org

Shrink PNG files. Advanced lossy compression for PNG images
that preserves full alpha transparency.

Note: This project is not affiliated with tinypng.org or Voormedia B.V.

Important: You require an API key which you may obtain from
info@tinypng.org (as of October 2012).

Besides specifying keys via command line arguments you can
    1. Set the environment variable TINYPNG_API_KEY
    2. Create a .tinypng.keys file in your home directory
    3. Create a tinypng.keys file in the current directory

Keyfiles must have one key per line. Invalid keys should
be removed as they slow down requests.

Usage:
    tinypng <png_files>...
            [--key=<key>] [--apikeys=<keyfile>]
            [--replace] [--quiet] [--verbose]
    tinypng -h | --help
    tinypng --version

Options:
    --key=<key>                 API Key
    --apikeys=<keyfile>         File with one key per line
    -h --help                   Show this screen
    -q --quiet                  Don't display api and file compression info
    --version                   Show version.

    -v --verbose                Noop (use --quiet to disable output)
"""
from __future__ import print_function

import sys
from docopt import docopt
from tinypng import get_shrink_file_info, write_shrunk_file, find_keys
from tinypng import __version__


def main(argv=sys.argv[1:]):
    version = 'TinyPNG API ' + __version__
    args = docopt(__doc__, argv=argv, version=version)
    keys = set(find_keys(args))

    if keys is None:
        print("Error: Could not find API key (see help).")
        return 1

    def pout(s):
        if args['--quiet']:
            return
        sys.stdout.write(s)
        sys.stdout.flush()

    for fpath in args['<png_files>']:
        cur_keys = keys.copy()
        for key in cur_keys:
            try:
                pout("Shrinking '%s' .. " % fpath)
                out_info = get_shrink_file_info(fpath, api_key=key)
                out = out_info['output']
                pout(" saved %02d%%\n" % (100 - (out['ratio'] * 100)))

                pout("Writing to '%s' .. " % out['filepath'])

                write_shrunk_file(out_info)

                pout("done.\n")
                break
            except ValueError:
                keys.remove(key)
                print('Invalid Key "%s"' % key)

    return 0


if __name__ == "__main__":
    sys.exit(main())
