/***
 * 添加FLASH对本地的安全权限，否则评测卡片无法使用
 * Author: jhwang
 * Date: 2014/7/17
 * @type {trust}
 *
 * @update:
 * yuwang 2014/08/21 修改trust方法，可动态传入需要设置的host。修复中文路径下策略文件重复写入的Bug。
 */

module.exports = trust

var fs = require('fs');
var path = require('path');
var iconv = require('iconv-lite');

/**
 * Flash信任文件编码
 * @type {string}
 * @const
 */
var TRUST_FILE_ENCODING = 'gb2312';

/**
 * 同步创建文件夹
 * @param dirName
 */
function mkdirSync(dirName) {
    if (dirName.match(/\b[a-zA-Z]:\.$/))         //这是windows盘符
        return;
    try {
        fs.mkdirSync(dirName);
    } catch(e) {
        if ( e.code != 'EEXIST' ) console.log(e);
    }
}

/**
 * 同步创建带父目录文件夹
 * @param dirpath
 */
function mkdirpSync(dirpath) {
    var parts = dirpath.split(path.sep);
    for (var i = 1; i <= parts.length; i++) {
        mkdirSync(path.join.apply(null, parts.slice(0, i)));
    }
}

/**
 * 拷贝安全策略配置文件
 * @param host
 */
function copySettings(host) {
    var appdata = process.env.APPDATA;

    var sysDir = appdata + '\\Macromedia\\Flash Player\\macromedia.com\\support\\flashplayer\\sys\\#' + host;
    mkdirpSync(sysDir);
    var targetFile = sysDir + '\\settings.sol';
    var sourceFile = __dirname + '\\settings.sol';
    fs.writeFileSync(targetFile, fs.readFileSync(sourceFile));
}

/**
 * 拷贝安全策略配置文件 到#local目录
 * @param host
 */
function copySettingsToLocal() {
    var appdata = process.env.APPDATA;
    var sysDir = appdata + '\\Macromedia\\Flash Player\\macromedia.com\\support\\flashplayer\\sys\\#local';
    var sysRoot = appdata + '\\Macromedia\\Flash Player\\macromedia.com\\support\\flashplayer\\sys';
    mkdirpSync(sysDir);
    var targetFile = sysDir + '\\settings.sol';
    var targetRootFile = sysRoot + '\\settings.sol';
    var sourceFile = __dirname + '\\settings.sol';

    fs.writeFileSync(targetFile, fs.readFileSync(sourceFile));
    fs.writeFileSync(targetRootFile, fs.readFileSync(sourceFile));
}

/**
 * 设置host默认信任
 * @param {...string} hosts host列表
 */
function trust(hosts) {
    copySettingsToLocal();
    var dstDir = path.resolve('');
    var str = '\r\n' + dstDir;
	//windows这个文件是ansi编码的
	var buf = iconv.encode(str, TRUST_FILE_ENCODING);
    var appdata = process.env.APPDATA;

    var trustDir = appdata + '\\Macromedia\\Flash Player\\#Security\\FlashPlayerTrust';
    mkdirpSync(trustDir);
    var trustCfg = trustDir + '/trust.cfg';

    console.log(trustCfg);

    fs.exists(trustCfg, function (exists) {
        if (exists) {
            var data =  iconv.decode(fs.readFileSync(trustCfg), TRUST_FILE_ENCODING);
            // 已经添加过信任则返回
            if (data.indexOf(dstDir) > -1) {
                return;
            }
            fs.appendFile(trustCfg, buf, null);
        } else {
            fs.appendFile(trustCfg, buf, function (err) {
                if (err) console.log(err);
            });
        }


    });

    for(var index= 0, len = arguments.length; index < len; index++) {
        copySettings(arguments[index]);
    }
}
