(function ($) {
    $.fn.customToast = function (data) {
        pushToast(setDefaults(data));
    };

    function setDefaults(data) {
        let elementData = data ? Object.assign({}, data) : {};
        elementData.type = elementData.type ? elementData.type : "success"; //success | error | alert | question
        elementData.title = generateTitle(elementData.type, data.localization, elementData.title);
        elementData.autoCloseDelay = elementData.autoCloseDelay ? elementData.autoCloseDelay : undefined; //in ms
        elementData.id = elementData.id ? elementData.id : undefined;

        return elementData;
    }

    function pushToast(data) {
        let $toastWrapper = $("#custom-toast-container");
        if (!$toastWrapper || $toastWrapper.length === 0) {
            $toastWrapper = $("<div id='custom-toast-container'></div>");
            $("body").append($toastWrapper);
        }

        let $toastElement = generateToast(data);
        $toastWrapper.append($toastElement);

        if (data.autoCloseDelay) {
            setTimeout(function () {
                $toastElement.fadeOut(300, function () { $(this).remove(); });
            }, data.autoCloseDelay);
        }
    }

    function generateToast(data) {
        let $toastElement = $("<div class='custom-toast' " + (data.id ? "id='" + data.id + "'" : "") + "></div>");

        let $toastIcon = $("<div class='custom-toast-type-icon custom-toast-" + data.type + "-icon'></div>");
        let $toastContent = $("<div class='custom-toast-content'><div class='custom-toast-title-row'><div class='custom-toast-title'>" + data.title + "</div><span class='custom-toast-title-close fa fa-times' onClick='closeToast(this)'></span></div><div class='custom-toast-message'>" + data.text + "</div></div>")

        $toastElement.append($toastIcon);
        $toastElement.append($toastContent);

        return $toastElement;
    }

    function generateTitle(type, localization, title) {
        if (title) return title;

        if (!localization || !localization[type])
            return $("#custom-toast-" + type).length === 0 ? type[0].toUpperCase() + type.slice(1) : $("#custom-toast-" + type).val();

        return localization[type];
    }
}(jQuery));

function closeToast(element) {
    $(element).closest(".custom-toast").remove();
}
