"use strict"; // Start of use strict

// Mobile window size
let vh = window.innerHeight * 0.01;
document.documentElement.style.setProperty('--vh', `${vh}px`);
window.addEventListener('resize', () => {
    let vh = window.innerHeight * 0.01;
    document.documentElement.style.setProperty('--vh', `${vh}px`);
});

function loading(div, status) {
    $(div).LoadingOverlay(status, {
        image: "",
        custom: '<div class="lds-ellipsis"><div></div><div></div><div></div><div></div></div>',
    });
}

// save profile details
var page_reload = false;
$(".save-profile").on('click', function(e) {
    var data = new FormData($('#profile-form')[0]);
    var url = $('#save_profile_url').val();
    $('.profile-error').hide();
    $.ajax({
        url: url,
        data: data,
        type: "POST",
        dataType: 'json',
        cache: false,
        contentType: false,
        processData: false,
        enctype: 'multipart/form-data',
        success: function(data) {

            $('.text-error').remove();
            if (data.success == true) {
                page_reload = true;
                $('.profile-success').html("Successfully Updated");
                $('.profile-success').show();
            } else {
                if ($.isArray(data.message)) {
                    $.each(data.message, function(key, field_array) {
                        $.each(field_array, function(field, error_list) {
                            $.each(error_list, function(error_key, error_message) {
                                $('[name=' + field + ']').after(`<small class="form-text text-danger text-error">` + error_message + `</small>`);
                            });
                        });
                    });
                } else {
                    $('.profile-error').html(data.message);
                    $('.profile-error').show();
                }
            }
        },
    });
});

// profile image upload
$(document).on("change", ".upload-image", function() {
    var uploadFile = $(this);
    var files = !!this.files ? this.files : [];
    if (!files.length || !window.FileReader) return; // no file selected, or no FileReader support

    if (/^image/.test(files[0].type)) { // only image file
        var reader = new FileReader(); // instance of the FileReader
        reader.readAsDataURL(files[0]); // read the local file
        reader.onloadend = function() { // set image data as background of div
            uploadFile.closest(".imgUp").find('img').remove();
            uploadFile.closest(".imgUp").find('.imagePreview').css("background-image", "url(" + this.result + ")");
        }
    }
});

$('#modalProfile').on('hidden.bs.modal', function() {
    if (page_reload) {
        page_reload = false;
        window.location.reload();
    }
});

$('.rooms-modal').on('hidden.bs.modal', function() {
    if (page_reload) {
        page_reload = false;
        window.location.reload();
    }
});

if ( $( ".cookiealert" ).length ) {

    var cookieAlert = document.querySelector(".cookiealert");
    var acceptCookies = document.querySelector(".acceptcookies");


    cookieAlert.offsetHeight;

    // Show the alert if we cant find the "acceptCookies" cookie
    if (!getCookie("acceptCookies")) {
        cookieAlert.classList.add("show");
    }

    // When clicking on the agree button, create a 1 year
    // cookie to remember user's choice and close the banner
    acceptCookies.addEventListener("click", function () {
        setCookie("acceptCookies", true, 365);
        cookieAlert.classList.remove("show");
        // dispatch the accept event
        window.dispatchEvent(new Event("cookieAlertAccept"))
    });

}

// Cookie functions from w3schools
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) === ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) === 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

$(".view-chatroom").on('click', function(e) {
    var room_id = $(this).attr('data-room');
    $('#chatroomList').modal('hide');
    get_chat_room(room_id);
});

function get_chat_room(edit_id){
    $.ajax({
        url: "https://chat.megawrzuta.pl/ajax/get-chatroom",
        data: {
            edit_room: edit_id,
            csrftoken: 'bMcU2Jth1bUzOX5g/1GAEW9aqmBMkgmQyD29SCCoagY='
        },
        type: "POST",
        beforeSend: function() {
            loading(".card-room-users", "show");
        },
        success: function(data) {
            $('.rooms-modal .modal-body').html(data);
            setTimeout(function(){ $('.rooms-modal').modal('show'); }, 500);
            $('#chatroomList').modal('hide');
            $('.dataTable').DataTable();
        },
        complete: function(){
            loading(".card-room-users", "hide");
        }
    });
}

// Update Chat Room information with ajax
$(document).on("click", '.update-chatroom', function(event) {
    var data = new FormData($('#chatroom-info')[0]);
    $('.chatroom-success').hide();
    $('.chatroom-error').hide();
    $.ajax({
        url: "https://chat.megawrzuta.pl/ajax/update-chatroom",
        data: data,
        type: "POST",
        dataType: 'json',
        contentType: false,
        processData: false,
        enctype: 'multipart/form-data',
        beforeSend: function() {
            loading(".card-room-info", "show");
        },
        success: function(data) {
            $('.text-error').remove();
            if(data.success == "true") {
                page_reload = true;
                $('.chatroom-success').html("Successfully Updated");
                $('.chatroom-success').show();
            }else{
                $.each( data.message, function( key, field_array ) {
                    $.each( field_array, function( field, error_list ) {
                        $.each( error_list, function( error_key, error_message ) {
                            $('[name='+field+']').after(`<small class="form-text text-danger text-error">`+error_message+`</small>`);
                        });
                    });
                });
            }

        },complete: function(){
            loading(".card-room-info", "hide");
        }
    });

    $('a[data-toggle="pill"]').on('shown.bs.tab', function (e) {

        $('.chatroom-success').hide();
        $('.chatroom-error').hide();
    });
});

// Update and manage users in chat rooms (kick and unkick)
$(document).on("click", ".chatroom-user-restriction", function(){
    var result = confirm("Are you sure?");
    if (result) {
        var current_row = $(this).closest('tr');
        var room_id = $('#room_id').val();
        var selected_user = $(this).attr("data-user");
        var restriction_type = $(this).attr("data-restriction-type");
        $.ajax({
            url: "https://chat.megawrzuta.pl/ajax/chatroom-user-restriction",
            data: {room_id : room_id, selected_user : selected_user, restriction_type : restriction_type,
            csrftoken: 'bMcU2Jth1bUzOX5g/1GAEW9aqmBMkgmQyD29SCCoagY='
            },
            type: "POST",
            beforeSend: function() {
                loading(".card-room-users", "show");
            },
            success: function(data) {
                if(restriction_type == "3"){
                    $(current_row).find('.kick-btn').css("display", "none");
                    $(current_row).find('.unkick-btn').css("display", "block");
                }else if (restriction_type == "1") {
                    $(current_row).find('.kick-btn').css("display", "block");
                    $(current_row).find('.unkick-btn').css("display", "none");
                }

                if(data.success == "true") {
                    $('.chatroom-success').html(data.message);
                    $('.chatroom-success').show();
                }else{
                    $('.chatroom-error').html(data.message);
                    $('.chatroom-error').show();
                }
            },
            complete: function(){
                loading(".card-room-users", "hide");
            }
        });
    }
});

$(document).on('change', '#is_protected', function() {
    if(this.checked) {
        $('.pin-area').show();
    }else{
        $('.pin-area').hide();
    }
});

$( document ).ready(function() {
    // init date dropdown
    $(".dob").dateDropdowns();
    $('.dataTable').DataTable();

});
