#!/usr/bin/python3
#
# Converts puz files to ipuz files
#

import argparse
import getopt
import json
import locale
import os
import signal
import sys
import textwrap

# set up our path to import our files
pkgdatadir = '/usr/share/crosswords/ipuz-convertor'
sys.path.insert(1, pkgdatadir)
import config

try:
    from jpzconvertor import JPZConvertor
except ImportError:
    JPZConvertor = None
try:
    from puzconvertor import PUZConvertor
except ImportError:
    PUZConvertor = None
try:
    from xdconvertor import XDConvertor
except ImportError:
    XDConvertor = None

# set up translations
localedir = '/usr/share/locale'
locale.bindtextdomain("crosswords", localedir)
locale.textdomain("crosswords")


def main():
    parser = argparse.ArgumentParser(prog='ipuz-convertor',
                                     description="ipuz-convertor converts a .puz file into an .ipuz file.",
                                     formatter_class=argparse.RawTextHelpFormatter)

    parser.add_argument('-v', '--version',
                        action='version', version=config.__version__)
    parser.add_argument('-i', '--input',
                        help=textwrap.dedent("""\
                            the filename for the .puz file to convert
                            (if not provided, it will read from stdin)"""),
                        default=None)
    parser.add_argument('-u', '--url',
                        help=textwrap.dedent("""\
                            A url to add to the URL field of the resulting ipuz file."""),
                        default=None)
    parser.add_argument('-r', '--intro',
                        help=textwrap.dedent("""\
                            Text to add to the intro field of the resulting ipuz file."""),
                        default=None)
    parser.add_argument('-n', '--notes',
                        help=textwrap.dedent("""\
                            Text to add to the notes field of the resulting ipuz file."""),
                        default=None)
    parser.add_argument('-l', '--license',
                        help=textwrap.dedent("""\
                            A license to add to the license field of the resulting ipuz file."""),
                        default=None)
    parser.add_argument('-t', '--type',
                        help=textwrap.dedent("""\
                            The type of crossword to convert from (jpz, puz, xd)"""),
                        choices=['jpz', 'puz', 'xd'],
                        default=None)
    parser.add_argument('-o', '--output',
                        help=textwrap.dedent("""\
                            the filename for the saved puzzle
                            (if not provided, it will print to stdout)"""),
                        default=None)

    args = parser.parse_args ()

    puz_type = None

    # Is there a filename?
    if args.input and not args.input == '-':
        with open(args.input, "rb") as f:
            data = f.read()
        if PUZConvertor is not None:
            if any(args.input.endswith(ext) for ext in PUZConvertor.EXTENSIONS):
                puz_type = 'puz'
        if JPZConvertor is not None:
            if any(args.input.endswith(ext) for ext in JPZConvertor.EXTENSIONS):
                puz_type = 'jpz'
        if XDConvertor is not None:
            if any(args.input.endswith(ext) for ext in XDConvertor.EXTENSIONS):
                puz_type = 'xd'
    else:
        if os.isatty(0):
            parser.print_help()
            sys.exit (0)
        data = sys.stdin.buffer.read()

    # Really cheap mime sniffing. This should be replaced by real
    # sniffing
    if PUZConvertor and PUZConvertor.MAGIC in data[:20]:
        puz_type = 'puz'
    elif JPZConvertor and JPZConvertor.MAGIC in data[:20]:
        puz_type = 'jpz'

    # This will manually override any detection we do
    if args.type:
        puz_type = args.type

    if not puz_type:
        print ("Unsupported file type")
        sys.exit (0)

    if PUZConvertor and puz_type == 'puz':
        convertor = PUZConvertor (data)
    elif JPZConvertor and puz_type == 'jpz':
        convertor = JPZConvertor (data)
    elif XDConvertor and puz_type == 'xd':
        convertor = XDConvertor (data)
    else:
        print ("No convertor available for type:", puz_type)
        sys.exit (0)

    ipuz_dict = convertor.convert_to_ipuz()

    # Update tags
    if args.url:
        ipuz_dict['url'] = args.url
    if args.notes:
        ipuz_dict['notes'] = args.notes
    if args.intro:
        ipuz_dict['intro'] = args.intro
    if args.license:
        ipuz_dict['org.gnome.libipuz:license'] = args.license

    ipuz_dict['origin'] = "Converted by %s - %s" % (config.__title__, config.__version__)

    # export the ipuz file
    if args.output:
        output = open (args.output, "w")
    else:
        output = sys.stdout
    json.dump (ipuz_dict, output)

if __name__ == "__main__":
    signal.signal(signal.SIGINT, signal.SIG_DFL)
    main ()
