/**
 * Created by long on 18/7/3.
 */

var appKeywords = require("./scripts/appKeywords");
var appLeaderboard = require("./scripts/appLeaderboard");
var fs = require("fs");
var config = require("./config")

var nodejieba = require("nodejieba");

var synonyms = require("node-synonyms");

var wordsFile = "./data/words.json";

var targetApps = process.argv.slice(2);

var words = [];
var appIndex = 0;

if(targetApps && targetApps.length) {
    handleLeaderboard(targetApps);
} else {
    if(!fs.existsSync(wordsFile)) {

        if(fs.existsSync(config.top10File)) {
            var topGames = fs.readFileSync(config.top10File, "utf8");
            topGames = JSON.parse(topGames);
            handleLeaderboard(topGames);
        } else {
            appLeaderboard(function(topGames) {
                handleLeaderboard(topGames);
            })
        }

    } else {
        handleWords();
    }
}

function handleLeaderboard(topGames) {
    var ids = [];
    for(var i = 0; i < topGames.length; i++) {
        var gd = topGames[i];

        var exclude = false;
        var include = false;
        if(gd.trackName) {
            for(var j = 0; j < config.includedWords.length; j++) {
                var gname = gd.trackName.toLowerCase();
                if(gname.indexOf(config.includedWords[j]) > -1) {
                    include = true;
                    break;
                }
            }
        } else {
            include = true;
        }


        if(!exclude && include) {
            ids.push(gd.appId || gd);
            console.log(gd.trackName || gd);
        }
    }
    console.log("一共参考游戏: " + ids.length, ids);
    allKeywords(ids);
}

function allKeywords(ids) {
    var id = ids[appIndex++];
    if(!id) {
        console.log("-------aso over--------");
        fs.writeFileSync(wordsFile, JSON.stringify(words));
        handleWords();
        return;
    }
    appKeywords(id, function(keys) {
        words = words.concat(keys);
        allKeywords(ids);
    })
}

function handleWords() {
   var words = fs.readFileSync(wordsFile, "utf8");
    words = JSON.parse(words);
    var result = [];
    for(var i = 0; i < words.length; i++) {
        //name: keyName,
        //num: rankNumber,
        //index: rankIndex,
        //apps: appsNum
        var w = words[i];
        if(!w) continue;
        var name = w.name;
        {
            var appsNum = w.apps;
            var hot = w.num;
            if(appsNum >= config.keyAppsMin && appsNum <= config.keyAppsMax && hot >= config.keyMin && hot < config.keyMax)
            {
                result.push(w);
            } else {
                //console.log(appsNum)
            }
        }
    }
    //按热度和app数进行排序
    result = result.sort(function(a, b) {
        if(a.num > b.num) return -1;
        else return 1;
        if(a.apps < b.apps) return -1;
        return 0;
    });
    console.log(result.length);
    calWords(result);
    //fs.writeFileSync("result.json", JSON.stringify(result))
}

function calWords(words) {
    var allNames = [];
    var allNames_en = [];
    for(var i = 0; i < words.length; i++) {
        var w = words[i].name;
        w = w.replace("-", "");
        w = w.replace(".", "");
        w = w.replace("~", "");
        w = w.replace("〜", "")
        w = w.replace(" ", "");
        if(isChinese(w)) {
            allNames.push(w);
        } else {
            if(allNames_en.indexOf(w) == -1) {
                allNames_en.push(w);
            }
        }
    }

    //抽取关键词
    var keys = nodejieba.extract(allNames.join(""), 300);

    var result = [];
    for(var i = 0; i < keys.length; i++) {
        var k = keys[i].word;
        if(config.isExcluded(k)) continue;
        if(result.indexOf(k) == -1)
        {
            result.push(k);
        }
    }

    console.log("关键词抽取:")
    console.log(result.join(","))

    var keys = filterWords(filterWords(result));

    console.log("关键词过滤:")
    var keyStr = keys.join("");
    console.log(keyStr);

    var count = 105;
    console.log(keyStr.slice(0, count));
    console.log(keyStr.slice(count, count*2));
    console.log(keyStr.slice(2*count, count*3));

    allNames_en = filterWords(filterWords(allNames_en, 100), 100)
    //console.log(allNames_en.join(" "))

    //doCutWords(result);
    //cutWords(allNames);
    //cutWords1(allNames);

}

function filterWords(words, unitCount) {
    if(!unitCount) unitCount = 2;
    var twoWords = [];
    for(var i = 0; i < words.length; i++) {
        var w = words[i];
        if(w.length <= unitCount && twoWords.indexOf(w) == -1) {
            twoWords.push(w);
        }
    }

    var wordsNeedFilter = {}
    for(var i = 0; i < words.length; i++) {
        var w = words[i];
        if(!w || !w.length) continue;
        for(var j = 0; j < twoWords.length; j++) {
            var twoWord = twoWords[j];
            var index = w.indexOf(twoWord);
            if(index > -1) {
                if(twoWord == w) {
                    //words[i] = "";
                } else if(!wordsNeedFilter[twoWord]) {
                    wordsNeedFilter[twoWord] = 1;
                } else {
                    words[i] = w.replace(twoWord, "");
                    wordsNeedFilter[twoWord]++;
                }
            }
        }
    }

    for(var tWord in wordsNeedFilter) {
        //console.log(tWord, wordsNeedFilter[tWord]);
        if(wordsNeedFilter[tWord] >= 1) {
            for(var i = 0; i < words.length; i++) {
                var w = words[i];
                if(w == tWord) {
                    words[i] = "";
                    break;
                }
            }
        }
    }

    return words;

    //console.log(keyStr)

}

//function cutWords(allNames) {
//    var result = [];
//    var words = [];
//    for(var i = 0; i < allNames.length; i++) {
//        var name = allNames[i];
//        words = words.concat(nodejieba.cutHMM(name));
//    }
//
//    words = words.sort(function(a, b) {
//        return b.length - a.length;
//    })
//
//    for(var j = 0; j < words.length; j++) {
//        var w = words[j];
//        if(!keysInArray(w, result, 1)) {
//            result.push(w);
//        }
//    }
//
//    console.log(result.join(""))
//}

//function cutWords1(allNames) {
//    synonyms.seg(allNames.join(""), true, true)
//        .then(function(words){
//            doCutWords(words);
//        });
//}

//function doCutWords(words) {
//    var result = [];
//    for (var i = 0; i < words.length; i++) {
//        var w = words[i];
//        if (result.indexOf(w) == -1) {
//            result.push(w);
//        }
//    }
//
//    result = result.sort(function (a, b) {
//        return b.length - a.length;
//    })
//
//    var finalResult = [];
//    for (var i = 0; i < result.length; i++) {
//        var w = result[i];
//        if (w.length < 2) continue;
//        //if(!keysInArray(w, finalResult, 1)) {
//        //    finalResult.push(w);
//        //}
//        filterArray(w, finalResult);
//        finalResult.push(w);
//    }
//    //console.log(keysInArray("博彩", finalResult.slice(0, finalResult.length - 1), 1));
//    var finalStr = finalResult.join("");
//    console.log(finalStr);
//    return finalResult;
//}

//function keysInArray(key, arr, n) {
//    if(!n) n = 1;
//    var count = 0;
//    for(var i = 0; i < arr.length; i++) {
//        var words = arr[i];
//        if(words.indexOf(key) > -1) {
//            if(++count >= n) {
//                return true;
//            }
//        }
//    }
//    return false;
//}

//function filterArray(key, arr) {
//    for(var i = 0; i < arr.length; i++) {
//        var words = arr[i];
//        var index = words.indexOf(key);
//        if(index > -1) {
//            arr[i] = words.replace(key, "");
//        }
//    }
//}

function isChinese(s) {
    //4E00 - 9FA5
    var code = ('' + s).charCodeAt(0);
    if (code >= 0x4E00 && code <= 0x9FA5) {
        return true;
    } else {
        return false;
    }
}