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

var now = new Date();
var day = now.toLocaleDateString();
day = day.replace(/-/g, "");

//aso指数
var api = "https://www.chandashi.com/keyword/coverrank.html";
//前10数量
var api = "https://www.chandashi.com/keyword/coverrank/type/top10/date/" + day + ".html";

var countInPage = 200;//一页多少个数据
var page = 0;
var totalPage = 10;

console.log(api);

//查询
//$.ajax(
//    { url: window.location.href,
//        data:{rank:1},
//        dataType:"json",
//        type:"POST",
//        async:true,
//        success:function(data) {
//            console.log(data);
//        }
//    });
var games = [];
var gameNames = [];
var gameIds = [];

function fetchPage(cb) {
    request({
        url: api,
        method: "POST",
        headers: {
            "Content-type": "application/json"
        },
        formData: {rank: (page * countInPage)}
    }, function(error, response, body){
        body = body.replace(/\\\//g, "/");
        body = JSON.parse(body);

        console.log("page: " + page, body.length)

        for(var i = 0; i < body.length; i++) {
            var d = body[i];
            if(d.genres == "游戏") {
                if(!config.only1500 || d.genreRank != "1500名以外") {
                    games.push(d);
                    gameNames.push(d.trackName);
                    gameIds.push(d.appId)
                }
            }
        }

        if(++page < totalPage) {
            setTimeout(function() {
                fetchPage(cb);
            }, 100)
        } else {
            console.log(games.length);
            if(cb) cb(games);
            fs.writeFileSync(config.top10File, JSON.stringify(games));
            console.log("-----over------");
        }
    });
}

module.exports = fetchPage;