'use strict';
exports.__esModule = true;
var cheerio = require("cheerio");
var rp = require("request-promise");
var log = require("./log");
// tslint:disable-next-line:no-var-requires
var cloudscraper = require('cloudscraper');
var isAuthenticated = false;
var isPremium = false;
var defaultHeaders = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64; x64; rv:58.0) Gecko/20100101 Firefox/58.0',
    'Connection': 'keep-alive',
    'Referer': 'https://www.crunchyroll.com/login'
};
function generateDeviceId() {
    var id = '';
    var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    for (var i = 0; i < 32; i++) {
        id += possible.charAt(Math.floor(Math.random() * possible.length));
    }
    return id;
}
function startSession() {
    return rp({
        method: 'GET',
        url: 'https://api.crunchyroll.com/start_session.0.json',
        qs: {
            device_id: generateDeviceId(),
            device_type: 'com.crunchyroll.iphone',
            access_token: 'QWjz212GspMHH9h',
            version: '2313.8',
            locale: 'enUS'
        },
        json: true
    })
        .then(function (response) {
        return response.data.session_id;
    });
}
function login(sessionId, user, pass) {
    return rp({
        method: 'POST',
        url: 'https://api.crunchyroll.com/login.0.json',
        form: {
            account: user,
            password: pass,
            session_id: sessionId,
            version: '2313.8'
        },
        json: true
    })
        .then(function (response) {
        if (response.error)
            throw new Error('Login failed: ' + response.message);
        return response.data;
    });
}
// TODO: logout
/**
 * Performs a GET request for the resource.
 */
function get(config, options, done) {
    authenticate(config, function (err) {
        if (err) {
            return done(err);
        }
        cloudscraper.request(modify(options, 'GET'), function (error, response, body) {
            if (error)
                return done(error);
            done(null, typeof body === 'string' ? body : String(body));
        });
    });
}
exports.get = get;
/**
 * Performs a POST request for the resource.
 */
function post(config, options, done) {
    authenticate(config, function (err) {
        if (err) {
            return done(err);
        }
        cloudscraper.request(modify(options, 'POST'), function (error, response, body) {
            if (error) {
                return done(error);
            }
            done(null, typeof body === 'string' ? body : String(body));
        });
    });
}
exports.post = post;
/**
 * Authenticates using the configured pass and user.
 */
function authenticate(config, done) {
    if (isAuthenticated || !config.pass || !config.user) {
        return done(null);
    }
    startSession()
        .then(function (sessionId) {
        defaultHeaders.Cookie = "sess_id=" + sessionId + "; c_locale=enUS";
        return login(sessionId, config.user, config.pass);
    })
        .then(function (userData) {
        /**
         * The page return with a meta based redirection, as we wan't to check that everything is fine, reload
         * the main page. A bit convoluted, but more sure.
         */
        var options = {
            headers: defaultHeaders,
            jar: true,
            url: 'http://www.crunchyroll.com/',
            method: 'GET'
        };
        cloudscraper.request(options, function (err, rep, body) {
            if (err) {
                return done(err);
            }
            var $ = cheerio.load(body);
            /* Check if auth worked */
            var regexps = /ga\('set', 'dimension[5-8]', '([^']*)'\);/g;
            var dims = regexps.exec($('script').text());
            for (var i = 1; i < 5; i++) {
                if ((dims[i] !== undefined) && (dims[i] !== '') && (dims[i] !== 'not-registered')) {
                    isAuthenticated = true;
                }
                if ((dims[i] === 'premium') || (dims[i] === 'premiumplus')) {
                    isPremium = true;
                }
            }
            if (isAuthenticated === false) {
                var error = $('ul.message, li.error').text();
                return done(new Error('Authentication failed: ' + error));
            }
            if (isPremium === false) {
                log.warn('Do not use this app without a premium account.');
            }
            else {
                log.info('You have a premium account! Good!');
            }
            done(null);
        });
    })["catch"](done);
}
/**
 * Modifies the options to use the authenticated cookie jar.
 */
function modify(options, reqMethod) {
    if (typeof options !== 'string') {
        options.jar = true;
        options.headers = defaultHeaders;
        options.method = reqMethod;
        return options;
    }
    return {
        jar: true,
        headers: defaultHeaders,
        url: options.toString(),
        method: reqMethod
    };
}
//# sourceMappingURL=my_request.js.map