let rowCells = [];

$('tbody').delegate("tr", "click", function(e){
    rowCells = e.target.parentElement.cells;
});

function updatePOI(){
    let data = {
        poiSelected: $('#tourist_selected').val(),
        card_country: $('#card_country').val(),
        loc_name: $('#loc_name').val(),
        address: $('#address').val(),
        city_id: $('#city-id').val(),
        description: $('#description').val(),
        feature_image: $('input[name="feature_image"]').val(),
        status: $('input[type="checkbox"][name="status"]').prop("checked") ? 1 : 0,
    };
    $.ajax({
        method: 'post',
        url: '/tools/updatePOI',
        dataType: 'json',
        data: data
    })
    .done(function(data) {
        alert(`${data.message}`);
        rowCells[0].innerText = $('#card_country').val();
        rowCells[2].innerText = $('#city-id option:selected').text();
        rowCells[3].innerText = $('#loc_name').val();
        rowCells[6].innerText = data.data.address;
        rowCells[7].innerText = data.data.plus_code;
        rowCells[9].innerText = $('#description').val();
        rowCells[10].innerText = $('#city-id option:selected').val();
        rowCells[12].innerText = $('input[name="feature_image"]').val();

        if($('input[name="status"]').prop("checked")) {
            rowCells[14].children[0].setAttribute('data-status', 't');
            rowCells[14].children[0].innerText = 'Deactive';
        } else {
            rowCells[14].children[0].setAttribute('data-status', 'f');
            rowCells[14].children[0].innerText = 'Public';
        }

        let aElem = $('#feature_image_preview')[0];
        let imgSrc = $('input[name="feature_image"]').val();
        let imgNotFound = `https://resources.float.sg/cards/notfound?size=80x80`
        if (imgSrc !== '') {
            aElem.style.display = 'unset';
            let imgElem = $('#image_preview')[0];
            if (imgSrc.includes('http')) {
                aElem.href = `${imgSrc}`;
                imgElem.src = `${imgSrc}?size=80x80`;
            } else {
                aElem.href = `${imgNotFound}`;
                imgElem.src = `${imgNotFound}`;
            }
        } else {
            $aElem.style.display = 'none';
        }
    })
    .fail(function(err) {
        let errors = Object.values(err.responseJSON.errors);
        let message = '';
        for (index in errors) {
            message += errors[index];
        }
        alert(message);
    })
}

function showAddPOIForm(){
    $('#tourist_selected').val('');
    $('#card_country').val('');
    $('#loc_name').val('');
    $('#address').val('');
    $('#city-id').val('');
    $('#description').val(''),
    $('input[name="feature_image"]').val(''),
    $('input[type="checkbox"][name="status"]').prop("checked", false);
    $('button[name="update"]').css('display', 'none');
    $('button[name="delete"]').css('display', 'none');
    $('button[name="go"]').css('display', 'block');
}