var Promise = window.Promise;
if (!Promise) {
    Promise = JSZip.external.Promise;
}

var info = "{\"contentProviders\":[],\"metadata\":[],\"broadcastReceivers\":[],\"broadcastReceiver\":[],\"libraries\":[],\"services\":[],\"type\":\"com.sunny.DeepLink.DeepLink\",\"androidMinSdk\":[\"7\"],\"activityMetadata\":[],\"assets\":[],\"native\":[],\"permissions\":[],\"activities\":[\"<activity android:exported=\\\"true\\\" android:name=\\\"com.sunny.DeepLink.DeepLinkActivity\\\">\\n      <intent-filter android:autoVerify = \\\"true\\\" >\\n        <action android:name=\\\"android.intent.action.VIEW\\\"/>\\n        <category android:name=\\\"android.intent.category.DEFAULT\\\"/>\\n        <category android:name=\\\"android.intent.category.BROWSABLE\\\"/>\\n        <data android:host = \\\"sunnythedeveloper.in\\\" android:scheme = \\\"https\\\" />\\n    <\\/intent-filter>\\n    <\\/activity>\\n\"]}";
/*==================================================================
    [ Validate ]*/
var input = $('.validate-input .input100');

function submitUserForm() {
    var response = grecaptcha.getResponse();
    var check = true;
    /*for (var i = 0; i < input.length; i++) {
        if (validate(input[i]) == false) {
            showValidate(input[i]);
            check = false;
        }
    }*/
    if (response.length == 0) {
        document.getElementById('g-recaptcha-error').innerHTML = '<span style="color:red;">This field is required.</span>';
        check = false;
    }
    if (check) {
        generateAix();
        document.getElementById("container-form").remove();
    }
}

function verifyCaptcha() {
    document.getElementById('g-recaptcha-error').innerHTML = '';
}

/**
 * Fetch the content and return the associated promise.
 * @param {String} url the url of the content to fetch.
 * @return {Promise} the promise containing the data.
 */
function urlToPromise(url) {
    return new Promise(function (resolve, reject) {
        JSZipUtils.getBinaryContent(url, function (err, data) {
            if (err) {
                reject(err);
            } else {
                resolve(data);
            }
        });
    });
}

function updatePercent(percent) {
    $("#progress_bar").removeClass("hide")
        .find(".progress-bar")
        .attr("aria-valuenow", percent)
        .css({
            width: percent + "%"
        });
}

function generateAix() {
    var zip = new JSZip();
    updatePercent(0);
    zip.file("com.sunny.DeepLink/extension.properties", urlToPromise("aix/com.sunny.DeepLink/extension.properties"), { binary: true });
    zip.file("com.sunny.DeepLink/components.json", urlToPromise("aix/com.sunny.DeepLink/components.json"), { binary: true });
    zip.file("com.sunny.DeepLink/classes.jar", urlToPromise("aix/com.sunny.DeepLink/classes.jar"), { binary: true });
    zip.file("com.sunny.DeepLink/files/AndroidRuntime.jar", urlToPromise("aix/com.sunny.DeepLink/files/AndroidRuntime.jar"), { binary: true });
    var inputShema = "";
    var inputHost = "";
    var form = document.getElementById("form");
    var childs = form.getElementsByClassName("form_e");
    var shemaHost = "";
        for (var i = 0; i < childs.length; i++) {
            var details = childs[i];
            var ch2 = details.children;
            inputShema = ch2[1].children[0].value;
            inputHost = ch2[2].children[0].value;
            inputPathPrefix = ch2[3].children[0].value;
            if(inputPathPrefix.length > 0){
                inputPathPrefix = " android:pathPrefix=\\\""+inputPathPrefix+"\\\"/>";
            }else{
                inputPathPrefix = "";
            }
            if(inputShema.length > 0 && inputHost.length > 0){
                shemaHost = shemaHost + "<data android:scheme=\\\""+inputShema+"\\\" android:host=\\\""+inputHost+"\\\""+ inputPathPrefix +" />";
            }
        }
    info = replaceAll(info, "<data android:host = \\\"sunnythedeveloper.in\\\" android:scheme = \\\"https\\\" />", shemaHost);
    zip.file("com.sunny.DeepLink/files/component_build_infos.json", info);
    zip.generateAsync({ type: "blob" }, function updateCallback(metadata) {
        var msg = "progression : " + metadata.percent.toFixed(2) + " %";
        if (metadata.currentFile) {
            msg += ", current file = " + metadata.currentFile;
        }
        //showMessage(msg);
        updatePercent(metadata.percent | 0);
    })
        .then(function callback(blob) {

            // see FileSaver.js
            saveAs(blob, "com.sunny.DeepLink.aix");
            //showMessage("done !");
        }, function (e) {
            //showError(e);
        });

}

$('.validate-form .input100').each(function () {
    $(this).focus(function () {
        hideValidate(this);
    });
});

function validate(input) {
    if ($(input).val().trim() == '') {
        return false;
    }
}

function showValidate(input) {
    var thisAlert = $(input).parent();

    $(thisAlert).addClass('alert-validate');
}

function hideValidate(input) {
    var thisAlert = $(input).parent();

    $(thisAlert).removeClass('alert-validate');
}

function escapeRegExp(string) {
    return string.replace(/[.*+\-?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

function replaceAll(str, find, replace) {
    return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}

(function ($) {
    "use strict";

    /*==================================================================
    [ Focus input ]*/
    $('.input100').each(function () {
        $(this).on('blur', function () {
            if ($(this).val().trim() != "") {
                $(this).addClass('has-val');
            } else {
                $(this).removeClass('has-val');
            }
        })
    })

})(jQuery);
