'use strict';

const fs = require('fs');
const Log = require('log');

const URL = require('./url');
const Codec = require('../codec');
const Client = require('../httpclient');

const log = new Log('debug');

const AppConfig = {
    clientid: 53999199,
    appid: 501004106
};

function writeFileAsync(filePath, data, options) {
    return new Promise((resolve, reject) => {
        fs.writeFile(filePath, data, options, error => {
            if (error) reject(error);
            resolve();
        });
    });
};

class QQ {
    constructor() {
        this.tokens = {
            ptwebqq: '',
            vfwebqq: '',
            psessionid: ''
        };
        this.selfInfo = {};
        this.buddy = {};
        this.discu = {};
        this.group = {};
        this.client = new Client();
    }

    async login() {
        let initCookies = {
            pgv_info: `ssid=s${Codec.randPgv()}`,
            pgv_pvid: Codec.randPgv()
        };
        this.client.setCookie(initCookies);
        await this.client.get(URL.loginPrepare);
        let qrCode = await this.client.get({ url: URL.qrcode, responseType: 'arraybuffer' });
        await writeFileAsync('/tmp/code.png', qrCode, 'binary');
        log.info('二维码下载完成，等待扫描...');
        require('child_process').exec('xdg-open /tmp/code.png');
        let scanSuccess = false;
        let quotRegxp = /'[^,]*'/g;
        let ptlogin4URL;
        do {
            let responseBody = await this.client.get({
                url: URL.getPtqrloginURL(this.client.getCookie('qrsig')),
                headers: { Referer: URL.qrsigReferer },
            });
            log.debug(responseBody);
            let arr = responseBody.match(quotRegxp).map(i => i.substring(1, i.length - 1));
            if (arr[0] === '0') {
                scanSuccess = true;
                ptlogin4URL = arr[2];
            }
        } while (!scanSuccess);
        log.info('二维码扫描完成');
        require('child_process').exec('rm /tmp/code.png');
        await this.client.get({
            url: ptlogin4URL,
            maxRedirects: 0,     // Axios follows redirect automatically, but we need to disable it here.
            headers: { Referer: URL.ptlogin4Referer }
        });
        this.tokens.ptwebqq = this.client.getCookie('ptwebqq');
        log.info('获取 ptwebqq 成功');
        let vfwebqqResp = await this.client.get({
            url: URL.getVfwebqqURL(this.tokens.ptwebqq),
            headers: { Referer: URL.vfwebqqReferer }
        });
        log.debug(vfwebqqResp);
        this.tokens.vfwebqq = vfwebqqResp.result.vfwebqq;
        log.info('获取 vfwebqq 成功');

    }
}

module.exports = QQ;
@@ -814,24 +814,151 @@
 c login() %7B%0A
+        // Step0: prepare cookies, pgv_info and pgv_pvid%0A        // http://pingjs.qq.com/tcss.ping.js  tcss.run & _cookie.init%0A
         let 
@@ -969,24 +969,24 @@
 Cookies = %7B%0A
-
             
@@ -1164,16 +1164,51 @@
 repare);
+%0A%0A        // Step1: download QRcode
 %0A       
@@ -1392,24 +1392,61 @@
 %EF%BC%8C%E7%AD%89%E5%BE%85%E6%89%AB%E6%8F%8F...');%0A
+        // open file, only for linux%0A
         requ
@@ -1489,32 +1489,52 @@
 /tmp/code.png');
+%0A%0A        // Step2: 
 %0A        let sca
@@ -1587,16 +1587,96 @@
 ,%5D*'/g;%0A
+        let ptqrloginURL = URL.getPtqrloginURL(this.client.getCookie('qrsig'));%0A
         
@@ -1781,24 +1781,17 @@
    url: 
-URL.getP
+p
 tqrlogin
@@ -1797,40 +1797,8 @@
 nURL
-(this.client.getCookie('qrsig'))
 ,%0A  
@@ -1835,21 +1835,25 @@
 er: URL.
-qrsig
+ptqrlogin
 Referer 
@@ -2179,24 +2179,70 @@
 '%E4%BA%8C%E7%BB%B4%E7%A0%81%E6%89%AB%E6%8F%8F%E5%AE%8C%E6%88%90');%0A
+        // remove file, for linux(or macOS ?)%0A
         requ
@@ -2287,16 +2287,142 @@
 e.png');
+%0A%0A        // Step3: find token 'vfwebqq' in cookie%0A        // NOTICE: the request returns 302 when success. DO NOT REJECT 302.
 %0A       
@@ -2746,16 +2746,59 @@
 qq %E6%88%90%E5%8A%9F');
+%0A%0A        // Step4: request token 'vfwebqq'
 %0A       
@@ -3084,24 +3084,79 @@
 ebqq %E6%88%90%E5%8A%9F');%0A%0A
+        // Step5: psessionid and uin%0A        // TODO: %0A
     %7D%0A%7D%0A%0Amod

add some comments