#!/usr/bin/env node

/**
 * UglifyCSS
 * Port of YUI CSS Compressor to NodeJS
 * Author: Franck Marcia - https://github.com/fmarcia
 * MIT licenced
 */

/**
 * cssmin.js
 * Author: Stoyan Stefanov - http://phpied.com/
 * This is a JavaScript port of the CSS minification tool
 * distributed with YUICompressor, itself a port
 * of the cssmin utility by Isaac Schlueter - http://foohack.com/
 * Permission is hereby granted to use the JavaScript version under the same
 * conditions as the YUICompressor (original YUICompressor note below).
 */

/**
 * YUI Compressor
 * http://developer.yahoo.com/yui/compressor/
 * Author: Julien Lecomte - http://www.julienlecomte.net/
 * Copyright (c) 2011 Yahoo! Inc. All rights reserved.
 * The copyrights embodied in the content of this file are licensed
 * by Yahoo! Inc. under the BSD (revised) open source license.
 */

const { defaultOptions, processString, processFiles } = require('./')
const { writeFileSync } = require('fs')

const UGLIFYCSS_VERSION = '0.0.29'

// Info namespace
const info = {}

// Print usage
info.help = _ => {
    console.log(`
        Usage: uglifycss [options] file1.css [file2.css [...]] > output
        options:
        --max-line-len n  add a newline every n characters
        --expand-vars     expand variables
        --ugly-comments   remove newlines within preserved comments
        --cute-comments   preserve newlines within and around preserved comments
        --convert-urls d  convert relative urls using the d directory as location target
        --debug           print full error stack on error
        --output f        put the result in f file
        --help            show this help
        --version         display version number`
        .replace(/^\s+/gm, '')
    )
}

// Print version
info.version = _ => {
    console.log(`uglifycss ${UGLIFYCSS_VERSION}`)
}

// Transform strings like "the-parameter" to "theParameter"
const par2var = param =>
    param.replace(
        /-(.)/g,
        (_, ch) => ch === '-' ? '' : ch.toUpperCase()
    )


// Parse parameters from command line
const parseArguments = argv => {

    const params = {
        options: defaultOptions,
        files: []
    }

    const len = argv.length

    for (let i = 2; i < len; i += 1) {

        // get "propertyName" from "--argument-name"
        let v = par2var(argv[i])

        // boolean parameters
        if (typeof params.options[v] === 'boolean') {
            params.options[v] = true

        // string parameter
        } else if (typeof params.options[v] === 'string') {
            params.options[v] = argv[i + 1] || ''
            i += 1

        // integer parameter
        } else if (typeof params.options[v] !== 'undefined') {
            params.options[v] = parseInt(argv[i + 1], 10)
            i += 1

        // help
        } else if (argv[i] === '--help') {
            return 'help'

        // version
        } else if (argv[i] === '--version') {
            return 'version'

        // file
        } else {
            params.files.push(argv[i])
        }
    }

    return params
}

// Entry
{
    // parameters
    const params = parseArguments(process.argv)

    // info
    if (params === 'help' || params === 'version') {
        return info[params]()
    }

    // files
    if (params.files.length) {
        const ugly = processFiles(params.files, params.options)
        if (params.options.output) {
            return writeFileSync(params.options.output, ugly)
        } else {
            return console.log(ugly)
        }
    }

    // no file, no stdin: help
    if (process.stdin.isTTY) {
        return info.help()
    }

    // stdin
    if (params.options.convertUrls) {
        return console.error('uglifycss: stdin input and --convert-urls are not compatible')
    }
    let content = ''
    process.stdin.on('data', part => content += part)
    process.stdin.on('end', _ =>
        console.log(processString(content, params.options))
    )
}
