"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var ora_1 = __importDefault(require("ora"));
var whatsapp_1 = require("../api/whatsapp");
var auth_1 = require("./auth");
var browser_1 = require("./browser");
var spinner = ora_1.default();
var shouldLoop = true;
var pjson = require('../../package.json');
var timeout = function (ms) {
    return new Promise(function (resolve) { return setTimeout(resolve, ms, 'timeout'); });
};
var waPage;
var qrTimeout;
function create(sessionId, puppeteerConfigOverride, customUserAgent) {
    return __awaiter(this, void 0, void 0, function () {
        var throwOnError, PAGE_UA, BROWSER_VERSION, SULLA_HOTFIX_VERSION, WA_VERSION, canInjectEarly, authenticated, autoRefresh, qrLoop, qrSpin, race, result, pre, VALID_SESSION;
        var _this = this;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (!sessionId)
                        sessionId = 'session';
                    spinner.start('Initializing whatsapp');
                    return [4, browser_1.initWhatsapp(sessionId, puppeteerConfigOverride, customUserAgent)];
                case 1:
                    waPage = _a.sent();
                    spinner.succeed();
                    throwOnError = puppeteerConfigOverride && puppeteerConfigOverride.throwErrorOnTosBlock == true;
                    return [4, waPage.evaluate('navigator.userAgent')];
                case 2:
                    PAGE_UA = _a.sent();
                    return [4, waPage.browser().version()];
                case 3:
                    BROWSER_VERSION = _a.sent();
                    SULLA_HOTFIX_VERSION = pjson.version;
                    return [4, waPage.evaluate(function () { return window.Debug ? window.Debug.VERSION : 'I think you have been TOS_BLOCKed'; })];
                case 4:
                    WA_VERSION = _a.sent();
                    console.log('Debug Info', {
                        WA_VERSION: WA_VERSION,
                        PAGE_UA: PAGE_UA,
                        SULLA_HOTFIX_VERSION: SULLA_HOTFIX_VERSION,
                        BROWSER_VERSION: BROWSER_VERSION
                    });
                    return [4, waPage.evaluate(function () { return (typeof webpackJsonp !== "undefined"); })];
                case 5:
                    canInjectEarly = _a.sent();
                    if (!canInjectEarly) return [3, 7];
                    spinner.start('Injecting api');
                    return [4, browser_1.injectApi(waPage)];
                case 6:
                    waPage = _a.sent();
                    spinner.start('WAPI injected');
                    return [3, 8];
                case 7:
                    if (throwOnError)
                        throw Error('TOSBLOCK');
                    console.log('Possilby TOS_BLOCKed');
                    _a.label = 8;
                case 8:
                    spinner.start('Authenticating');
                    return [4, auth_1.isAuthenticated(waPage)];
                case 9:
                    authenticated = _a.sent();
                    autoRefresh = puppeteerConfigOverride ? puppeteerConfigOverride.autoRefresh : false;
                    qrLoop = function () { return __awaiter(_this, void 0, void 0, function () {
                        return __generator(this, function (_a) {
                            switch (_a.label) {
                                case 0:
                                    if (!shouldLoop)
                                        return [2];
                                    console.log(' ');
                                    return [4, auth_1.retrieveQR(waPage, sessionId, autoRefresh, throwOnError)];
                                case 1:
                                    _a.sent();
                                    console.log(' ');
                                    qrTimeout = timeout((puppeteerConfigOverride ? (puppeteerConfigOverride.qrRefreshS || 10) : 10) * 1000);
                                    return [4, qrTimeout];
                                case 2:
                                    _a.sent();
                                    if (autoRefresh)
                                        qrLoop();
                                    return [2];
                            }
                        });
                    }); };
                    if (!authenticated) return [3, 10];
                    spinner.succeed('Authenticated');
                    return [3, 14];
                case 10:
                    spinner.info('Authenticate to continue');
                    qrSpin = ora_1.default();
                    qrSpin.start('Loading QR');
                    qrSpin.succeed();
                    qrLoop();
                    race = [];
                    race.push(auth_1.isInsideChat(waPage).toPromise());
                    if (puppeteerConfigOverride && puppeteerConfigOverride.killTimer) {
                        race.push(timeout(puppeteerConfigOverride.killTimer * 1000));
                    }
                    return [4, Promise.race(race)];
                case 11:
                    result = _a.sent();
                    if (!(result == 'timeout')) return [3, 13];
                    console.log('Session timed out. Shutting down');
                    return [4, kill()];
                case 12:
                    _a.sent();
                    throw new Error('QR Timeout');
                case 13:
                    shouldLoop = false;
                    clearTimeout(qrTimeout);
                    spinner.succeed();
                    _a.label = 14;
                case 14:
                    pre = canInjectEarly ? 'Rei' : 'I';
                    spinner.start(pre + "njecting api");
                    return [4, browser_1.injectApi(waPage)];
                case 15:
                    waPage = _a.sent();
                    spinner.succeed("WAPI " + pre + "njected");
                    if (!canInjectEarly) return [3, 17];
                    spinner.start('Checking if session is valid');
                    return [4, timeout(5000)];
                case 16:
                    _a.sent();
                    _a.label = 17;
                case 17: return [4, waPage.evaluate(function () { return window.Store && window.Store.Msg ? true : false; })];
                case 18:
                    VALID_SESSION = _a.sent();
                    if (!VALID_SESSION) return [3, 19];
                    spinner.succeed('Whatsapp is ready');
                    return [2, new whatsapp_1.Whatsapp(waPage)];
                case 19:
                    spinner.fail('The session is invalid. Retrying');
                    return [4, kill()];
                case 20:
                    _a.sent();
                    return [4, create(sessionId, puppeteerConfigOverride, customUserAgent)];
                case 21: return [2, _a.sent()];
            }
        });
    });
}
exports.create = create;
var kill = function () { return __awaiter(void 0, void 0, void 0, function () {
    return __generator(this, function (_a) {
        switch (_a.label) {
            case 0:
                shouldLoop = false;
                if (qrTimeout)
                    clearTimeout(qrTimeout);
                return [4, waPage.close()];
            case 1:
                _a.sent();
                return [4, waPage.browser().close()];
            case 2:
                _a.sent();
                return [2];
        }
    });
}); };
