var fs = require("fs");
var request = require("request");
var config = require("./../config")

function appWords(appid, cb) {
    var api = 'https://www.chandashi.com/apps/keywordcover/appId/' + appid + '/country/' + config.country + '.html';
    console.log(api);
    //发送带cookie的请求
    var requestOption = {
        url: api,
        headers: {
            'Cookie': config.cookieStr
        }
    };
    request(requestOption, function(err, response, body) {
        var result = !body ? null : body.match(/keywordData = \[\[(.*)\]\];/g);
        if(!result || !result.length) {
            console.log("匹配keywordData错误或无关键词，检查网页源码进行纠正");
            if(cb) cb(null);
        } else {
            result = result [0];
            result = result.replace("keywordData = ", "");
            result = result.replace("keywordData=", "");
            result = result.replace("]];", "]]");

            result = JSON.parse(result);

            //过滤4605以上，排名20以内的
            var filterdResult = [];
            var keysResult = [];

            for(var i = 0; i < result.length; i++) {
                var r = result[i];
                var rankNumber = r[2];
                if(rankNumber >= 4605)
                {
                    var rankIndex = r[1];
                    rankIndex = rankIndex.split("|");
                    rankIndex = parseInt(rankIndex[0]);
                    if(rankIndex <= config.maxIndex) {
                        var keyName = r[0];
                        var appsNum = r[3];
                        filterdResult.push({
                            name: keyName,
                            num: rankNumber,
                            index: rankIndex,
                            apps: appsNum
                        });
                        keysResult.push(keyName);
                    }
                }
            }
            if(cb) cb(filterdResult);
        }
    })
}

//appWords("1053336483", function(ws) {
//    console.log(ws);
//})

module.exports = appWords;