"""
The MIT License (MIT)

Copyright (c) 2016 Marcelo Maia

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

*************************************************************
 Amazon kindlegen(Linux) V2.9 build 1028-0897292
 A command line e-book compiler
 Copyright Amazon.com and its Affiliates 2014
*************************************************************

Usage : kindlegen [filename.opf/.htm/.html/.epub/.zip or directory] [-c0 or -c1 or c2] [-verbose] [-western] [-o <file name>]
Note:
   zip formats are supported for XMDF and FB2 sources
   directory formats are supported for XMDF sources
Options:
   -c0: no compression
   -c1: standard DOC compression
   -c2: Kindle huffdic compression
   -o <file name>: Specifies the output file name. Output file will be created in the same directory as that of input file. <file name> should not contain directory path.
   -verbose: provides more information during ebook conversion
   -western: force build of Windows-1252 book
   -releasenotes: display release notes
   -gif: images are converted to GIF format (no JPEG in the book)
   -locale <locale option> : To display messages in selected language
      en: English
      de: German
      fr: French
      it: Italian
      es: Spanish
      zh: Chinese
      ja: Japanese
      pt: Portuguese
      ru: Russian
      nl: Dutch
"""

import argparse
import os


def valid_input(param):
    base, ext = os.path.splitext(param)
    extensions = ('.opf', '.htm', '.epub', '.html', '.zip')
    if ext.lower() not in extensions:
        raise argparse.ArgumentTypeError('File must have any of {} extensions'.format(extensions))
    elif not os.path.exists(param):
        raise argparse.ArgumentTypeError('Filename {} does not exist'.format(param))
    return param


def valid_output(param):
    base, ext = os.path.splitext(param)
    extension = '.mobi'
    if ext.lower() != extension:
        raise argparse.ArgumentTypeError('File must be {} extension'.format(extension))
    return param


parser = argparse.ArgumentParser()
parser.add_argument("filename",
                    help="filename.opf/.htm/.html/.epub/.zip or directory",
                    type=valid_input)
parser.add_argument("-v", "--verbose",
                    help="provides more information during ebook conversion",
                    action="store_true",
                    dest="verbose")

parser.add_argument("-o", "--output",
                    help="output file",
                    type=valid_output)

compression = parser.add_mutually_exclusive_group()
compression.add_argument("-c0",
                         action="store_true",
                         help="no compression")
compression.add_argument("-c1",
                         action="store_true",
                         help="standard DOC compression")
compression.add_argument("-c2",
                         action="store_true",
                         help="Kindle huffdic compression")

args = parser.parse_args()


def build_kindlegen_cmd(args):
    compr = '-c0'
    if args.c1:
        compr = '-c1'
    elif args.c2:
        compr = '-c2'
    # TODO: disparar um warning para a pessoa procurar o kindlegen
    kindlegen_executable = 'kindlegen'
    cmd = '{kindlegen} {filename} {compression}'.format(kindlegen=kindlegen_executable,
                                                        filename=args.filename,
                                                        compression=compr)
    if args.verbose:
        cmd += ' -verbose'
    if args.output:
        cmd += ' -o {output}'.format(output=args.output)
    return cmd
