#!/usr/bin/python

##############################################################################
#   CEED - Unified CEGUI asset editor
#
#   Copyright (C) 2011-2012   Martin Preisler <martin@preisler.me>
#                             and contributing authors (see AUTHORS file)
#
#   This program is free software: you can redistribute it and/or modify
#   it under the terms of the GNU General Public License as published by
#   the Free Software Foundation, either version 3 of the License, or
#   (at your option) any later version.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU General Public License
#   along with this program.  If not, see <http://www.gnu.org/licenses/>.
##############################################################################

"""Data migration command line tool
"""

import sys
import argparse

def printFormatInfo(compat):
    print("Editor native version: '%s'" % (compat.manager.EditorNativeType))
    print("")

    print("Formats by CEGUI version:")
    for ceguiVersion in sorted(compat.manager.CEGUIVersionTypes, reverse = True):
        print(" - %s uses '%s'" % (ceguiVersion, compat.manager.CEGUIVersionTypes[ceguiVersion]))

    print("")

    print("All formats that have detectors:")
    for detector in compat.manager.detectors:
        print(" - '%s', extensions: %s" % (detector.getType(), ", ".join(detector.getPossibleExtensions())))

    print("")

def main():
    parser = argparse.ArgumentParser(
        formatter_class = argparse.RawDescriptionHelpFormatter,
        description = "Migrate given files using compatibility layers of the editor",
        epilog = """Supported compatibility managers:
 - imageset
 - layout
 - scheme
 - looknfeel
 - font

Example of usage:
 # show all known imageset format strings
 ceed-migrate imageset

 # migrate imageset from CEGUI 0.7 to CEGUI 0.8 format
 ceed-migrate --sourceType "CEGUI imageset 1" --targetType "CEGUI imageset 2" imageset sourcefile.imageset targetfile.imageset

 # migrate layout from CEGUI 0.7 to CEGUI 0.8 format
 ceed-migrate --sourceType "CEGUI layout 3" --targetType "CEGUI layout 4" layout sourcefile.layout targetfile.layout\n
"""
        )

    parser.add_argument("category", type = str,
                        help = "Which compatibility category to use ('imageset', 'layout').")
    parser.add_argument("--sourceType", type = str, default = "Auto", required = False,
                        help = "What is the source type of the data, if omitted, the type will be guessed")
    parser.add_argument("--targetType", type = str, default = "Native", required = False,
                        help = "What should the target type be. If omitted, editor's native type is used")

    parser.add_argument("input", metavar = "INPUT_FILE", type = argparse.FileType("r"),
                        help = "Input file to be processed.", nargs = "?")
    parser.add_argument("output", metavar = "OUTPUT_FILE", type = argparse.FileType("w"),
                        help = "Output / target file path.", nargs = "?")

    args = parser.parse_args()

    import ceed.compatibility

    if args.category == "imageset":
        from ceed.compatibility import imageset as compat

    elif args.category == "layout":
        from ceed.compatibility import layout as compat

    elif args.category == "scheme":
        from ceed.compatibility import scheme as compat

    elif args.category == "looknfeel":
        from ceed.compatibility import looknfeel as compat

    elif args.category == "font":
        from ceed.compatibility import font as compat

    else:
        print("Provided compatibility is not valid, such a compatibility module doesn't exist or ceed-migrate doesn't support it yet!")
        sys.exit(1)

    if args.input is None or args.output is None:
        printFormatInfo(compat)
        print("Both input and output file paths have to be present for migration "
            "to occur. This list is shown if any of them is missing.")
        sys.exit(0)

    data = args.input.read()

    sourceType = args.sourceType if args.sourceType != "Auto" else compat.manager.guessType(data, args.input.name)
    targetType = args.targetType if args.targetType != "Native" else compat.manager.EditorNativeType

    print("\nMigrating %s (%s) -> %s (%s)\n" % (args.input.name, sourceType, args.output.name, targetType))

    outputData = ""
    try:
        outputData = compat.manager.transform(sourceType, targetType, data)
        args.output.write(outputData)
        print("Performed migration from '%s' to '%s'.\ninput size: %i bytes\noutput size: %i bytes" % (sourceType, targetType, len(data), len(outputData)))
        sys.exit(0)

    except ceed.compatibility.LayerNotFoundError as e:
        print(e)
        sys.exit(1)

if __name__ == "__main__":
    main()
