#!/usr/bin/env coffee

fs               = require 'fs'
{Logger}         = require 'crafting-guide-common'
{ModVersionParser} = require 'crafting-guide'
{ModVersion}       = require 'crafting-guide'

########################################################################################################################

if process.argv.length is 3
    sourceFileName = process.argv[2]
    targetFileName = process.argv[2]
else if process.argv.length is 4
    sourceFileName = process.argv[2]
    targetFileName = process.argv[3]
else
    console.error """

    USAGE: reformat <source> (<target>)

        Reformats a given recipe book into the latest version of the recipe book
        format. This includes alphabetizing entries, simplifying item lists, and
        upgrading to the latest version.

        If given a single argument, the named file will be replaced with the
        reformatted version. If two arguments are given, then the output will be
        written to the second file. If a "-" is given as the second file, the
        output will be written to stdout.

    """
    process.exit -1

global.logger = new Logger level:Logger.WARNING

try
    text       = fs.readFileSync sourceFileName, 'UTF-8'
    parser     = new ModVersionParser model:new ModVersion modSlug:'', version:''
    modVersion = parser.parse text
    text       = parser.unparse(modVersion).trim().replace(/^\s\s*$/gm, '') + '\n\n'

    if targetFileName is '-'
        console.log text
    else
        fs.writeFileSync targetFileName, text, encoding:'UTF-8'
catch e
    console.error e.stack
