var fs = require("fs");
var request = require("request");

var types = ['游戏',
    '动作游戏',
    '探险游戏',
    '街机游戏',
    '桌面游戏',
    '扑克牌游戏',
    '娱乐场游戏',
    '骰子游戏',
    '教育游戏',
    '家庭游戏',
    '音乐游戏',
    '智力游戏',
    '赛车游戏',
    '角色扮演游戏',
    '模拟游戏',
    '体育游戏',
    '策略游戏',
    '小游戏',
    '文字游戏',
    //以下是appstore上有的类别
    '儿童',
    '竞速游戏',
    '聚会游戏',
    '卡牌游戏',
    '模拟游戏',
    '问答游戏',
    '益智解谜',
    '音乐'
];

var args = process.argv.slice(2);
var type = args[0] || types[0];

var api = "http://rest.appbk.com/word/get_word_rank?c=type&start=0&limit=max";

//登http://www.appbk.com/rank/word后，在http请求的cookie那里把cookie拷贝过来就可以了
var cookieStr = 'ci_session=a%3A5%3A%7Bs%3A10%3A%22session_id%22%3Bs%3A32%3A%22d06874557a88437adb573debaa2834a3%22%3Bs%3A10%3A%22ip_address%22%3Bs%3A14%3A%22100.116.223.94%22%3Bs%3A10%3A%22user_agent%22%3Bs%3A117%3A%22Mozilla%2F5.0+%28Macintosh%3B+Intel+Mac+OS+X+10_13_1%29+AppleWebKit%2F604.3.5+%28KHTML%2C+like+Gecko%29+Version%2F11.0.1+Safari%2F604.3.5%22%3Bs%3A13%3A%22last_activity%22%3Bi%3A1530525701%3Bs%3A9%3A%22user_data%22%3Bs%3A0%3A%22%22%3B%7Dfde61b10c8ee98a5fd022b7e1e8eb525';
var cookieStr = 'ci_session=a:5:{s:10:"session_id";s:32:"d06874557a88437adb573debaa2834a3";s:10:"ip_address";s:14:"100.116.223.94";s:10:"user_agent";s:117:"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_1) AppleWebKit/604.3.5 (KHTML, like Gecko) Version/11.0.1 Safari/604.3.5";s:13:"last_activity";i:1530525701;s:9:"user_data";s:0:"";}fde61b10c8ee98a5fd022b7e1e8eb525'
cookieStr = cookieStr.split("; ").join(";");
console.log(cookieStr);

var result = "";
var template = fs.readFileSync("template.html", "utf8");

fetchPage(type, 1000, function(result){
    //template = template.replace("~~~", result);
    //fs.writeFileSync("result.html", template);
    console.log(result);
    console.log("-------over--------")
})


function fetchPage(type, limit, cb) {
    var url = api.replace('type', type);
    url = url.replace('max', limit || 1000);
    console.log("请求：", url);
    request({
        url: url,
        headers: {
            "Cookie": cookieStr,
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'
        }
    }, function(err, response, body) {
        console.log(err, body);
        body = unescape(JSON.parse(body));
        if(cb) cb(body);

    })
}