'use strict';

require('source-map-support/register');

var url = require('url');
var getPage = require('./modules/getPage');
var getIconLinks = require('./modules/getIconLinks');
var downloadIcons = require('./modules/download/downloadIcons');
var findBestIcon = require('./modules/findBestIcon');

function isHttps(pageUrl) {
    return url.parse(pageUrl).protocol === 'https:';
}

function makeHttps(pageUrl) {
    var parsed = url.parse(pageUrl);
    parsed.protocol = 'https:';
    return url.format(parsed);
}

function main(pageUrl) {
    var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];


    var bestWithPref = function bestWithPref(icons) {
        return findBestIcon(icons, options.ext);
    };

    return getPage(pageUrl).then(function (dom) {
        return getIconLinks(pageUrl, dom);
    }).then(downloadIcons).then(bestWithPref).then(function (result) {
        if (result || isHttps(pageUrl)) {
            return result;
        }

        var httpsUrl = makeHttps(pageUrl);
        return main(httpsUrl, options);
    });
}

module.exports = main;
//# sourceMappingURL=index.js.map