var tableHeadings = ["Sr.No","Image","Is black and white?", "Category","Keywords","Credits","Approval Action"]
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();
    createTable(database);
    showDataTable();
});
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]);
        $(th).css('color', 'black');
        $(tr).append(th);
    }
    $(thead).append(tr);
    $("#dataTable").append(thead);
    tbody = document.createElement('tbody');
    $(tbody).prop('id', 'tableData');                    //tbody
    $("#dataTable").append(tbody);
    createTBody(imageData);
}

function showDataTable() {
    initialiseDataTable = false;
    $('#dataTable').DataTable().destroy();  // This line is causing the error
    $('#dataTable').removeAttr('width').DataTable({
        "autoWidth": false,
        "orderable": false,
        'columnDefs': [
        {
            orderable: false,
            targets: [1, 2, 4, 5, 6]
        }
        ]
    });
    $('.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']);
        if (imageData[i].keyword.endsWith(","))
        {
            imageData[i].keyword = imageData[i].keyword.slice(0,-1);
        }
        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="is_grey_clicked(this)" style="cursor:pointer" checked></h6>');
            idCnt++;
        }
        else{
            $($(tr).children()[idCnt]).html('<input type="checkbox" class="checkbox" onclick="is_grey_clicked(this)" style="cursor:pointer"></h6>'); idCnt++;
        }
        $($(tr).children()[idCnt]).html('<h6 style="cursor:pointer" onclick="edit_category_clicked(this);">'+imageData[i].category+'</h6>'); idCnt++;
        $($(tr).children()[idCnt]).html('<h6 style="cursor:pointer" onclick="edit_keywords_clicked(this);">'+imageData[i].keyword+'</h6>'); idCnt++;
        $($(tr).children()[idCnt]).html('<h6 style="cursor:pointer" onclick="edit_credits_clicked(this);">'+imageData[i].credits+'</h6>'); idCnt++;
        $($(tr).children()[idCnt]).html('<div style="display:inline-flex"><button class="button btn_approval" onclick="approve_resource(this)">Approve</button></br><button class="button btn_delete" onclick="delete_resource(this)">Delete</button></div>'); idCnt++;
        // $($(tr).children()[idCnt]).html('<h6>'+imageData[i].credits+'</h6>'); idCnt++;
        // $($(tr).children()[idCnt]).html(i + 1); idCnt++;
        // $($(tr).children()[idCnt]).html(i + 1); idCnt++;
        /* $($(tr).children()[idCnt]).html('<i class="fa fa-plus" onclick="addCategory(this)"></i>'); idCnt++; */
    }
}

function is_grey_clicked(ele){
    var checkFlag = 0;
    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);
            
        },
        error: function () {
            alert('Error');
        }
    });
}

function edit_category_clicked(ele){
    console.log($(ele).parent().parent().data('id'));
    $(ele).hide();
    category = $(ele).text();
    $(ele).parent().append('<div><input type="text" value="'+category+'"><button class="save_btn" type="button" onclick="save_category(this,category);">Save</button></div>');
}

function save_category(ele,category){
    new_category = ($(ele).prev().val()).trim();
        
    if(category!=new_category && new_category!=''){
        $.ajax({
            type: 'POST',
            url: save_category_link,
            data: {
                category: category,
                new_category: new_category,
                id: $(ele).parent().parent().parent().data('id'),
                csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
            },
            success: function (response) {
                response = JSON.parse(response);
                $(ele).parent().prev().text(response['msg']['category_list']);
                $(ele).parent().prev().parent().next().find('h6').text(response['msg']['keyword_list']);
                $(ele).parent().hide();
                $(ele).parent().prev().show();
                $(ele).parent().remove();
            },
            error: function () {
                alert('Error');
            }
        });
        
    }
    else{
        $(ele).parent().hide();
        $(ele).parent().prev().show();
        $(ele).parent().remove();
    }
    
}

function edit_keywords_clicked(ele){
    console.log($(ele).parent().parent().data('id'));
    $(ele).hide();
    keywords = $(ele).text();
    $(ele).parent().append('<div><input type="text" value="'+keywords+'"><button class="save_btn" type="button" onclick="save_keywords(this,keywords);">Save</button></div>');
}

function save_keywords(ele,keywords){
    new_keywords = ($(ele).prev().val()).trim();
    if(new_keywords.endsWith(','))
        new_keywords = new_keywords.slice(0,-1)

    console.log(keywords,new_keywords);

    if(keywords!=new_keywords && new_keywords!=''){
        $.ajax({
            type: 'POST',
            url: save_keywords_link,
            data: {
                keywords: keywords,
                new_keywords: new_keywords,
                id: $(ele).parent().parent().parent().data('id'),
                csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
            },
            success: function (response) {
                response = JSON.parse(response);
                $(ele).parent().prev().text(response['msg']);
                $(ele).parent().hide();
                $(ele).parent().prev().show();
                $(ele).parent().remove();
            },
            error: function () {
                alert('Error');
            }
        });        
    }
    else{
        $(ele).parent().hide();
        $(ele).parent().prev().show();
        $(ele).parent().remove();
    }    
}


function edit_credits_clicked(ele){
    console.log($(ele).parent().parent().data('id'));
    $(ele).hide();
    credits = $(ele).text();
    $(ele).parent().append('<div><input type="text" value="'+credits+'"><button class="save_btn" type="button" onclick="save_credits(this,credits);">Save</button></div>');
}

function save_credits(ele,credits){
    new_credits = ($(ele).prev().val()).trim();
    console.log(credits,new_credits);

    if(credits!=new_credits && new_credits!=''){
        $.ajax({
            type: 'POST',
            url: save_credits_link,
            data: {
                credits: credits,
                new_credits: new_credits,
                id: $(ele).parent().parent().parent().data('id'),
                csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
            },
            success: function (response) {
                response = JSON.parse(response);
                $(ele).parent().prev().text(response['msg']);
                $(ele).parent().hide();
                $(ele).parent().prev().show();
                $(ele).parent().remove();
            },
            error: function () {
                alert('Error');
            }
        });        
    }
    else{
        $(ele).parent().hide();
        $(ele).parent().prev().show();
        $(ele).parent().remove();
    }    
}


function approve_resource(ele){
    $("#loader").show();
    $.ajax({
        type: 'POST',
        url: approval_link,
        data: {
            id: $(ele).parent().parent().parent().data('id'),
            csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
        },
        success: function (response){
            response = JSON.parse(response);
            $("#loader").hide();
            if(response['msg']=='approved'){
                $(ele).parent().parent().parent().remove();
            }
        },
        error: function () {
            alert('Error');
        }
    });
    
}

function delete_resource(ele){
    $("#loader").show();
    $.ajax({
        type: 'POST',
        url: deletion_link,
        data: {
            id: $(ele).parent().parent().parent().data('id'),
            csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
        },
        success: function (response){
            response = JSON.parse(response);
            $("#loader").hide();
            if(response['msg']=='deleted'){
                $(ele).parent().parent().parent().remove();
            }
            else{
                alert(response['msg']);
            }
        },
        error: function () {
            alert('Error');
        }
    });
    
}

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();
}

