var tableHeadings = ["Sr.No", "Images", "Is black and white?","Keywords", "Edit"];
var editFlag = false;
var checkFlag=0;
var initialiseDataTable = true;

$(document).ready(function () {
    /***scroll to top */
    $(window).scroll(function () {
        if ($(this).scrollTop() > 50) {
            $('#back-to-top').fadeIn();
        } else {
            $('#back-to-top').fadeOut();
        }
    });
    // scroll body to 0px on click
    $('#back-to-top').click(function () {
        $('body,html').animate({
            scrollTop: 0
        }, 400);
        return false;
    });
    getCategory();
    
});

function getCategory() {
   
    $.ajax({
        type: 'GET',
        url: category_link,
        success: function (response) {
            console.log(response);
            var categoryArr = JSON.parse(response);
            createCategory(categoryArr);
        },
        error: function () {
            alert('Error');
        }
    });
}


function createCategory(categoryArr) {
    for (var i = 0; i < categoryArr.length; i++) {
        var a = document.createElement('a');
        $(a).prop('class', 'dropdown-item');
        $(a).text(categoryArr[i]);
        $('.dropdown-menu').append(a);
        $(a).on('click', function () {
            searchCategory(this)
        })
    }
}

function searchCategory(ele) {
    categoryName = $(ele).text();
    $("#loader").show();
    $('.dataTableDiv').hide();
    $('#dropdownBtn').text(categoryName);
    $('#categoryName').hide();
    $.ajax({
        type: 'GET',
        url: search_category_link,
        data: {
            keyword: categoryName,
            csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
        },
        success: function (response) {
            $("#loader").hide();
            $('.dataTableDiv').show();
            var imageData = JSON.parse(response);
            console.log(imageData);
            $('#dataTable').empty();
            $('#categoryName').show();
            $('#categoryName').text('Showing ' + imageData.length + ' entries of ' + categoryName);
            createTable(imageData);
            showDataTable(); 
        },
        error: function () {
            alert('Error');
        }
    });

}

function createTable(imageData) {
    var thead, tr, th, tbody;
    thead = document.createElement('thead');                //thead
    tr = document.createElement('tr');
    for (var i = 0; i < tableHeadings.length; i++) {
        th = document.createElement('th');
        $(th).prop('id','tableHead'+(i+1));
        $(th).text(tableHeadings[i]);
        $(tr).append(th);
    }
    $(thead).append(tr);
    $("#dataTable").append(thead);

    tbody = document.createElement('tbody');
    $(tbody).prop('id', 'tableData');                    //tbody
    $("#dataTable").append(tbody);
    createTBody(imageData);
    //showDataTable();
}

function showDataTable() {                              //show data table
    initialiseDataTable = false;
    $('#dataTable').DataTable().destroy();
    $('#dataTable').removeAttr('width').DataTable({
        "autoWidth": false,
        "orderable": false,
        'columnDefs': [
        {
            orderable: false,
            targets: [1,2,3,4] }
        ]
    });
    $('.dataTableDiv').show();
}

function createTBody(imageData)                     //tbody
{
    var idCnt;
    
    for (var i = 0; i < imageData.length; i++) {

        tr = document.createElement('tr');
        $(tr).data("rowData", i);
        $(tr).data("id", imageData[i]['id']);
        var keywords = imageData[i].keyword.split(",");
        for (var k = 0; k < tableHeadings.length; k++) {
            td = document.createElement('td');
            $(tr).append(td);
        }
        $("tbody").append(tr);
        idCnt = 0;
        $($(tr).children()[idCnt]).html(i + 1); idCnt++;
        $($(tr).children()[idCnt]).html('<img data-toggle="modal" data-target="#myModal" data="'+imageData[i].url+'" onclick="showModal(this)" class="img-responsive imgThumbnail noPadding"  src=' + imageData[i].thumb_url + '>'); idCnt++;
        
        if(imageData[i]['is_grey']==true)
            $($(tr).children()[idCnt]).html('<input type="checkbox" class="checkbox" onclick="checkboxClicked(this)" checked>');
        else
            $($(tr).children()[idCnt]).html('<input type="checkbox" class="checkbox" onclick="checkboxClicked(this)">'); 
        idCnt++;


        // $($(tr).children()[idCnt]).html('<input type="checkbox" class="checkbox" onclick="checkboxClicked(this)">'); idCnt++;

        var addIcon = document.createElement("i");
            $(addIcon).prop('class','addIcon fa fa-plus-circle ');
            $(addIcon).css('display','none');
            $(addIcon).on('click', function () {
                addCategory(this);
            })
            $($(tr).children()[idCnt]).append(addIcon);
            $($(tr).children()[idCnt]).append('<span class="spans">'+keywords+'</span>');
        
        var div = document.createElement('div');
        $(div).prop('id','parentTagDiv'+(i+1));
        $($(tr).children()[idCnt]).append(div);

        for (var j = 0; j < keywords.length; j++) {
            var inputDiv = document.createElement('div');
            // inputDiv.style = "display:flex;";
            $(inputDiv).prop('class', 'col-12 col-sm-12 col-lg-12 col-md-12 col-lg-12');

            var input = document.createElement('input');
            $(input).prop('type', 'text');
            $(input).prop('class', ' my-1 ml-1 chip');
            $(input).prop('value', keywords[j]);
            //$(input).text(keywords[j]);
            $(input).prop('disabled', true);
            $(div).append(inputDiv);
            
            var deleteIcon = document.createElement('i');
            $(deleteIcon).prop('class', 'icon deleteIcon fa fa-trash');
            $(deleteIcon).on('click', function () {
                deleteCategory(this);
            })
            $(inputDiv).append(input);
            $(inputDiv).append(deleteIcon);
            $('.icon').css('visibility','hidden');
        } idCnt++;
        $($(tr).children()[idCnt]).html('<i class="fa fa-edit" onclick="editCategory(this)"></i><i class="saveIcon fa fa-check" style="display:none;" onclick="saveCategory(this)"></i>'); idCnt++;
        /* $($(tr).children()[idCnt]).html('<i class="fa fa-plus" onclick="addCategory(this)"></i>'); idCnt++; */
    }
}


function checkboxClicked(ele){
    if($(ele).prop("checked") == true)
        checkFlag=1;
    else
        checkFlag=0;

    $.ajax({
        type: 'POST',
        url: mark_resource_color_link,
        data: {
            status: checkFlag,
            id:$(ele).parent().parent().data('id'),
            csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
        },
        success: function (response) {
            console.log(response);
            /* location.reload(true); */
        },
        error: function () {
            alert('Error');
        }
    });
}


function editCategory(ele) {
    editFlag = true;
    
    $(ele).css({'display':'none'});
    $(ele).next().css({'display':'block'});
   
    var eleData = $($(ele).parent()).parent().children()[3];
    var saveIconPath = $($(ele).parent()).siblings()[3];
    $($(saveIconPath).find('.addIcon ')).css('display','block');

    $($(eleData).find('.icon')).css('visibility','visible');
    $(eleData).find(".chip").prop('disabled', false);
    
    /* $($(eleData).children().find('input')).each(function(){
        if($(this).val()){
            tags_arr.push($(this).val());
        }
    });
    console.log(tags_arr); */
}

function addCategory(ele) {
    editFlag = true;
    var eleData = $(ele).siblings()[1];
    console.log(eleData);
    var inputDiv = document.createElement('div');
    $(inputDiv).prop('class', 'col-12 col-sm-12 col-lg-12 col-md-12 col-lg-12');

    var input = document.createElement('input');
    $(input).prop('type', 'text');
    $(input).prop('class', ' my-1 ml-1 chip');
    $(input).prop('disabled', false);
    $(eleData).append(inputDiv);
    //$(eleData).append('<span class="spans">'+keywords+'</span>');
    var deleteIcon = document.createElement('i');
    $(deleteIcon).prop('class', 'icon deleteIcon fa fa-trash');
    $(deleteIcon).css('visibility','hiddden');
    $(deleteIcon).on('click', function () {
        deleteCategory(this);
    })
    $(input).focus();
    $(inputDiv).append(input);
    $(inputDiv).append(deleteIcon);
}

function saveCategory(ele) {
    $('.saveIcon').css({ 'display': 'none' });
    $('.fa-edit').css({ 'display': 'block' });
    $('.addIcon').css({'display':'none'});

    var eleData = $($(ele).parent()).parent().children()[3];
    $($(eleData).find('.icon')).css('visibility', 'hidden');
    $(eleData).find(".chip").prop('disabled', true);

    var tags_arr = [];
    var parent = $($(ele).parent()).parent().children()[3];
    
    $($(parent).children().find('input')).each(function () {
        if ($(this).val()) {
            tags_arr.push($(this).val());
        }
    });

    var spanEle= $(eleData).children()[1];
    $(spanEle).text(tags_arr.join());
    console.log(tags_arr)
    
    url_link = search_link + $(ele).parent().parent().data('id');
    if (tags_arr.length > 0) {
        $.ajax({
            type: 'POST',
            url: url_link,
            data: {
                keyword: tags_arr.join(),
                csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
            },
            success: function (response) {
                console.log(response);
                /* location.reload(true); */
            },
            error: function () {
                alert('Error');
            }
        });
    }
}

function showModal(ele) {
    var imageSrc = $(ele).attr('data');
    $('#modalImage').prop('src', imageSrc);
}


function deleteCategory(ele){
    console.log($(ele));
    $($(ele).parent()).remove();
}

