/**
 * ts-cli.js
 * Copyright (c)2000 - 2017 Samsung Electronics Co., Ltd. All rights reserved.
 *
 * Contact:
 * Sungmin Kim <sm.art.kim@samsung.com>
 * Jonghwan Park <iwin100.park@samsung.com>
 * Kitae Kim <kt920.kim@samsung.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Contributors:
 * - S-Core Co., Ltd
**/

'use strict';

process.title = 'ts-cli';

var optimist = require('optimist');
var winston = require('winston');
require('date-format-lite');

var tsBuild = require('./lib/ts-build.js');
var tsFullBuild = require('./lib/ts-full-build.js');
var tsPull = require('./lib/ts-pull.js');
var tsPush = require('./lib/ts-push.js');
var tsDownload = require('./lib/ts-download.js');
var tsRelease = require('./lib/ts-release.js');
var init = require('../../core/plugin/init.js');


init.loadPlugins({
    locations: [__dirname + '/../../plugins'],
    type: ['core', 'common', 'client']
});

var log = new (winston.Logger)({
    transports: [
        new (winston.transports.File)({
            filename: '.ts-cli.log',
            timestamp: function () {
                var now = new Date();

                return now.format('YYYY-MM-DD hh:mm:ss.SS');
            },
            handleExceptions: true,
            json: false,
            level: 'verbose'
        }),
        new (winston.transports.Console)({
            handleExceptions: true,
            colorize: true,
            formatter: function (opts) {
                return winston.config.colorize(opts.level, opts.level.toUpperCase() + ' ' + (opts.message ? opts.message : '') +
                    (opts.meta && Object.keys(opts.meta).length ? '\n\t' + JSON.stringify(opts.meta) : ''));
            },
            level: 'info'
        })
    ],
    exceptionHandlers: [new winston.transports.File({
        filename: 'logException.log'
    })],
    exitOnError: false
});

// get host information
var usageMessage =
    'This tool is command line interface for Tizen Studio develop\n\n' +
    'Usage: $0 <SUBCOMMAND> [OPTS]\n\n' +
    'Subcommands:\n' +
    '  build               Build a package\n' +
    '  full-build          Full build packages\n' +
    '  create-installer    Create Tizen Studio installer\n' +
    '  create-image        Create Tizen Studio image\n' +
    '  push                Push the packages to local repository\n' +
    '  pull                Pull the packages to local repository from remote repository server\n' +
    '  download            Download the packages to local from remote repository server\n' +
    'Subcommand usage:\n' +
    '  build               ts-cli build --repository <repository path> [--source <source path>] [--clean] [--push-package [--force]]\n' +
    '  full-build          ts-cli full-build --repository <repository path> [--source <source path>] [--clean] [--force] [--exclude <exclude path list>] [--clone-source]\n' +
    '  create-instller     ts-cli create-installer --repository <repository path> --meta <meta package list> [--url <base repository URL>] \n' +
    '                             [--exclude-meta <meta package list>] [--title <Installer title>] [--output <installer name>] [--base-snapshot <base snapshot>]\n' +
    '  create-image        ts-cli create-image --repository <repository path> [--url <base repository URL>]\n' +
    '                             [--exclude-meta <meta package list>] [--skip-integrity] [--output <image name>] [--base-snapshot <base snapshot>]\n' +
    '  push                ts-cli push --package <package file path|list> --local-repo <repository path> [--force]\n' +
    '  pull                ts-cli pull --remote-repo <remote repository URL> --local-repo <repository path> [--force] [--os <os name | all>] [--base-snapshot <snapshot name>]\n' +
    '  download            ts-cli download --repository <repository path> --package <package file path|list> [--os <os name | all>] [--base-snapshot <snapshot name>]\n';

var argv = optimist.usage(usageMessage)
    .alias({
        c: 'clean',
        f: 'force',
        h: 'help',
        o: 'os',
        p: 'push-package',
        P: 'package',
        r: 'repository',
        s: 'source',
        u: 'url',
        x: 'exclude',
        M: 'meta',
        X: 'exclude-meta',
        S: 'skip-integrity',
        t: 'title',
        O: 'output',
        b: 'base-snapshot',
        cs: 'clone-source',
        rr: 'remote-repo',
        lr: 'local-repo'})
    .boolean(['clean', 'force', 'help', 'push-package', 'pull', 'clone-source'])
    .default('s', process.cwd())
    .string(['os', 'package', 'repository', 'source', 'url', 'exclude', 'meta', 'exclude-meta', 'title', 'base-snapshot'])
    .describe('h', 'display help')
    .describe('c', 'clean build')
    .describe('p', 'push the package(s) to local repository')
    .describe('P', 'single package file path or package files with seperator comma. ex) -P test1.zip | -P test1.zip,test2.zip')
    .describe('f', 'skip version comparison and push or pull packages by force. new packages will overwrite existing ones.')
    .describe('o', 'os name ex) all | ubunut-32 | ubuntu-64 | windows-32 | windows-64 | macos-64')
    .describe('r', 'repository path. local directory path or http url. ex) ./repository/develop | http://download.tizen.org/sdk/tizenstudio/official')
    .describe('u', 'url')
    .describe('s', 'source path')
    .describe('x', 'exclude path list')
    .describe('X', 'exclude meta list')
    .describe('M', 'meta list')
    .describe('S', 'check if dependent packages in repository exist or not')
    .describe('t', 'installer title')
    .describe('O', 'image or install output name')
    .describe('b', 'base snapshot name for package pull')
    .describe('cs', 'copy source to workspace')
    .describe('rr', 'remote repository url')
    .describe('lr', 'local repository path')
    .argv;

var subCmds = argv._;

if (argv.h) {
    optimist.showHelp();
    process.exit(0);
}

// validate sub command
if (!subCmds || subCmds.length === 0) {
    console.error('Sub-Command must be specified!');
    optimist.showHelp();
    process.exit(-1);
}

switch (subCmds[0]) {
case 'build':
    tsBuild.build(argv, log);
    break;
case 'full-build':
    tsFullBuild.build(argv, log);
    break;
case 'create-installer':
    tsRelease.createInstaller(argv, log);
    break;
case 'create-image':
    tsRelease.createImage(argv, log);
    break;
case 'push':
    tsPush.push(argv, log);
    break;
case 'pull':
    tsPull.pull(argv, log);
    break;
case 'download':
    tsDownload.download(argv, log);
    break;
default:
    console.error('Invalid sub-command!: \'' + subCmds + '\'');
    process.exit(-1);
}
