$(document).ready(function () {

    $('#nic_new_img_btn').click(function(){
        $('#nic_new_img_modal').modal('show');
        get_new_db_images();
        $('#nic_images_to_visit').attr("disabled", false);
        $('#nic_images_to_exam').attr("disabled", false);
    });

    $('.close').click(function(){
        $('#' + $(this).data('target')).hide();
    });

    var cookie_life = new Date();
    cookie_life.setTime(cookie_life.getTime() + (20 * 60 * 1000));
    $.cookie('images_timestamp', null, { expires: 0 });
    check_cookies();
    setInterval(() => check_cookies(), 5000);


    function check_cookies()
    {
        if (!document.hidden) {
            if ($('#nic_saving').length == 0)
            {
                var url = '/new_images_monitoring'
                if ($.cookie('images_timestamp'))
                    url = '/new_images_monitoring?timestamp='+$.cookie('images_timestamp')
                $.ajax({
                    type:'GET',
                    url: url,
                    processData: false,  // tell jQuery not to process the data
                    contentType: false,  // tell jQuery not to set contentType
                    success: (data) => {
                        for (msg_num in data['result'])
                        {
                            if (data['result'][msg_num]['timestamp'] > $.cookie('images_timestamp'))
                            {
                                startRemoteUnvRec(data['result'][msg_num]['src']);
                            }
                            if($.cookie('images_timestamp') == null)
                            {
                                startRemoteUnvRec(data['result'][msg_num]['src']);
                            }
                        }
                        $.cookie('images_timestamp', data['timestamp'], { expires: cookie_life });
                        if (data['length'] > 0)
                        {
                            $('#nic_new_img_btn').show();
                        }
                        else
                        {
                            $('#nic_new_img_btn').hide();
                        }

                    },
                    error:function (jqXHR, exception) {
                        after_error();
                    }
                });
            }
        }
    }

    function startRemoteUnvRec(src){
//        console.log('start_remote_unvisit_image_diagnostics');
        var message = {
            src: src
        }
        lang = getUrlParameter('lang');
        $.ajax({
            type:'POST',
            data: JSON.stringify(message),
            url: '/start_remote_unvisit_image_diagnostics'+'?lang='+lang,
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            success: (data) => {

                //Если модалка активна
                if($('#nic_new_img_modal').hasClass('show'))
                {
                    get_new_db_images();
                }
            },
            error:function (jqXHR, exception) {

            }
        });

    }

    var getUrlParameter = function getUrlParameter(sParam) {
        var sPageURL = window.location.search.substring(1),
            sURLVariables = sPageURL.split('&'),
            sParameterName,
            i;

        for (i = 0; i < sURLVariables.length; i++) {
            sParameterName = sURLVariables[i].split('=');

            if (sParameterName[0] === sParam) {
                return typeof sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
            }
        }
        return false;
    };

    $('#nic_images_to_exam').click(function(){
        $('#nic_images_to_exam').attr("disabled", true);
        var image_ids = [];
        $.each($('.img-checkbox'), function(e) {
            if($(this).is(':checked'))
                image_ids.push($(this).data('id'));
        });
        var message = {
            'image_ids': image_ids
        }
        lang = getUrlParameter('lang');
        $.ajax({
            type:'POST',
            data: JSON.stringify(message),
            url: '/nic_images_to_exam'+'?lang='+lang,
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            success: (data) => {
                if(data['success'] == true)
                {
                    if(lang == 'en')
                        window.location.href = '/med_exam?visit_id='+data['visit_id']+'&lang=en';
                    else
                        window.location.href = '/med_exam?visit_id='+data['visit_id']+'&lang=ru';
                }
                else
                    $('#nic_images_to_exam').attr("disabled", false);
            },
            error:function (jqXHR, exception) {
                $('#nic_images_to_exam').attr("disabled", false);
            }
        });
    });

    $('#nic_images_to_visit').click(function(){
        $('#nic_images_to_visit').attr("disabled", true);
        var image_ids = [];
        $.each($('.img-checkbox'), function(e) {
            if($(this).is(':checked'))
                image_ids.push($(this).data('id'));
        });
        var message = {
            'image_ids': image_ids
        }
        lang = getUrlParameter('lang');
        $.ajax({
            type:'POST',
            data: JSON.stringify(message),
            url: '/nic_images_to_visit'+'?lang='+lang,
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            success: (data) => {
                if(data['success'] == true)
                {
//                    if(lang == 'en')
//                        window.location.href = '/visit/'+data['patient_id']+'?lang=en&nic_visit=true';
//                    else
//                        window.location.href = '/visit/'+data['patient_id']+'?nic_visit=true';
                    if(lang == 'en')
                        window.location.href = '/visit/new_visit'+'?lang=en&nic_visit=true&visit_id='+data['visit_id'];
                    else
                        window.location.href = '/visit/new_visit'+'?nic_visit=true&visit_id='+data['visit_id'];
                }
                else
                    $('#nic_images_to_visit').attr("disabled", false);
            },
            error:function (jqXHR, exception) {
                $('#nic_images_to_visit').attr("disabled", false);
            }
        });
    });

    $('#nic_remove_images').click(function(){
        var image_ids = [];
        $.each($('.img-checkbox'), function(e) {
            if($(this).is(':checked'))
                image_ids.push($(this).data('id'));
        });
        var message = {
            'image_ids': image_ids
        }
        $.ajax({
            type:'POST',
            data: JSON.stringify(message),
            url: '/remove_nic_images',
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            success: (data) => {
                get_new_db_images();
            },
            error:function (jqXHR, exception) {

            }
        });
    });

    function get_new_db_images(){
        // Доделать чекбоксы для
        $('#new_images_selector').empty();
        lang = getUrlParameter('lang');
        $.ajax({
            type:'GET',
            url: '/get_new_db_images'+'?lang='+lang,
            processData: false,  // tell jQuery not to process the data
            contentType: false,  // tell jQuery not to set contentType
            success: (data) => {
                $('#new_images_selector').empty();
                for(i in data['result']['groups'])
                {
                    form_check = document.createElement('div');
                    form_check.setAttribute('class', 'form_check');
                    checkbox = document.createElement('input');
                    checkbox.setAttribute('type', 'checkbox');
                    checkbox.setAttribute('class', 'form-check-input check-group me-2');
                    checkbox.setAttribute('data-id', 'group_' + data['result']['groups'][i]);
                    checkbox.setAttribute('data-group', data['result']['groups'][i]);

                    label = document.createElement('label');
                    label.setAttribute('for', 'group_' + data['result']['groups'][i]);
                    label.setAttribute('class', 'form-check-label');

                    h3 = document.createElement('h3');
                    h3.innerHTML = data['result']['groups'][i]
                    label.appendChild(h3);
                    form_check.appendChild(checkbox);
                    form_check.appendChild(label);
                    document.getElementById("new_images_selector").appendChild(form_check);

                    pics = data['result'][data['result']['groups'][i]];
                    for(j in pics){
                    var pic = pics[j];
                    div = document.createElement('div');
                    div.setAttribute('class', 'col-xs-4 col-md-3 col-lg-2 col-4 p-1 m-0');

                    custom_control = document.createElement('div');
                    custom_control.setAttribute('class', 'custom-control custom-checkbox image-checkbox');

                    checkbox = document.createElement('input');
                    checkbox.setAttribute('type', 'checkbox');
                    checkbox.setAttribute('class', 'custom-control-input img-checkbox');
                    checkbox.setAttribute('id', 'chk' + pic['id']);
                    checkbox.setAttribute('data-id', pic['id']);
                    checkbox.setAttribute('data-group', data['result']['groups'][i]);

                    label = document.createElement('label');
                    label.setAttribute('for', 'chk' + pic['id']);
                    label.setAttribute('class', 'custom-control-label image-checkbox-label');

                    img = document.createElement('img');
                    img.setAttribute('class', 'img-fluid');
                    img.setAttribute('alt', '#');
                    img.setAttribute('src', '/img/'+pic['hash_name']);
                    label.appendChild(img);
                    custom_control.appendChild(checkbox);
                    custom_control.appendChild(label);
                    div.appendChild(custom_control);
                    document.getElementById("new_images_selector").appendChild(div);
                    }
                    $('#new_images_selector').append('<hr>');

                }
                $('.check-group').click(function(){
                    var group = $(this).data('group');
                    if($(this).is(':checked'))
                        $.each($('.img-checkbox'), function(e) {
                            if($(this).data('group') == group)
                                $(this).prop('checked', true);
                        });
                    else
                        $.each($('.img-checkbox'), function(e) {
                            if($(this).data('group') == group)
                                $(this).prop('checked', false);
                        });
                });
                $('.img-checkbox').click(function(){
                    var group = $(this).data('group');
                    var all_checked = true;
                    if($(this).is(':checked'))
                        $.each($('.img-checkbox'), function(e) {
                            if($(this).data('group') == group)
                                if($(this).is(':checked') == false)
                                {
                                    all_checked = false
                                }

                        });
                    else
                    {
                        $.each($('.check-group'), function(e) {
                            if($(this).data('group') == group)
                                $(this).prop('checked', false);
                        });
                        all_checked = false
                    }
                    if (all_checked == true)
                    {
                        $.each($('.check-group'), function(e) {
                            if($(this).data('group') == group)
                                $(this).prop('checked', true);
                        });
                    }
                })
            },
            error:function (jqXHR, exception) {

            }
        });

    }

});
