<template>
    <table id="search_tab_datatable" class="">
        <thead v-html="tableHead">
            
        </thead>
        <tbody>

        </tbody>
    </table>
</template>

<style>
    /* datatable proper*/
    .dataTables_empty {
        text-align: center;
        line-height: 10;
        font-size: 18px;
    }

    /* datatable button */
    .dt-button-collection .dropdown-menu {
        display: block !important;
        margin: 0;
        border: 1px solid #6c757d;
        border-top-left-radius: 0;
        border-top-right-radius: 0;
        padding-bottom: 0;
    }
    .dt-button-collection .dt-button {
        font-family: "Poppins", sans-serif;
        font-size: 13px;
        padding: 5px;
        background-color: #6c757d;
        color: white;
        width: 133px;
    }
    .dt-button-collection .dt-button:hover {
        background-color: rgb(248, 148, 6);
        color: white;
    }
    .dt-button-collection .dropdown-item {
        margin-bottom: 4px !important;
    }

    .datatable-toolbar .dt-buttons button.buttons-collection {
        width: 135px;
    }

    /* datatable toolbar */
    .datatable-toolbar {
        display: flex;
        justify-content: center;
        margin-bottom: 8px;
    }
    .datatable-toolbar > div {
        margin-left: 10px !important;
        margin-right: 10px !important;
    }
    .datatable-toolbar .dt-buttons {
        height: 30px;
    }
    .datatable-toolbar .dt-buttons button {
        border-radius: 4px;
    }
    .datatable-toolbar .dataTables_length {
        line-height: 16px;
    }
    .datatable-toolbar .dataTables_length label {
        margin: 0;
    }
    .datatable-toolbar .dataTables_length label .custom-select {
        line-height: 16px;
        width: auto !important;
        height: 36px !important;
        border: solid 1px #6c757d;
        outline: 0; 
        color: white !important;
        background: -moz-linear-gradient(top, #6c757d, #6c757d 1px, #6c757d 25px);
        background: -webkit-gradient(linear, left top, left 25, from(#6c757d), color-stop(4%, #6c757d), to(#6c757d));
    }
    .datatable-toolbar .dataTables_length label .custom-select option {
        /*appearance: none;*/
        font-family: "Poppins", sans-serif;
        font-size: 13px;
        background-color: #6c757d;
        color: white;
    }
    .datatable-toolbar .dataTables_length label .custom-select option:hover {
        background-color: rgb(248, 148, 6);
    }
    .datatable-toolbar .pagination {
        margin: 0 !important;
    }
    .datatable-toolbar .pagination a.page-link {
        padding: 0.6rem .75rem;
    }
    .datatable-toolbar .page-item.active .page-link {
        background: #6c757d;
    }
    .datatable-toolbar .pagination>li>a, .datatable-toolbar .pagination>li>span{
        border:1px solid #6c757d !important;
    }

    /* image block */
    .datatable-image-wrapper {
        position: relative;
        cursor: pointer;
        width: 199px !important; 
        height: 170px !important;
        margin-left: 10px;
        margin-right: 10px;
        margin-bottom: 10px;
        padding-top: 7px;
        padding-bottom: 10px !important;
        overflow: visible;
    }
    
    .datatable-image-wrapper:hover .gallery-img-buttons {
        display: block;
    }

    .datatable-image-wrapper img {
        display: block; 
        height: auto; 
        max-width: 100%; 
        max-height: 170px; 
        margin: auto; 
        position: relative; 
        top: 50%; transform: translateY(-50%);

        margin-top: 2px;
    }

    .datatable-image-wrapper img:hover {
        padding: 1px;
        outline: 2px dashed rgb(248, 148, 6) !important; /*#6c757d;*/
    }

    .datatable-image-wrapper .gallery-img-buttons {
        display: none;
        position: absolute;
        bottom: 0px; 
        right: 7px; 
        font-size:0;
    }

    .datatable-image-wrapper .gallery-img-buttons .gallery-img-btn {
        font-size: 22px; 
        /*
        background-color: #6c757d;
        color: white;
        border: 1px solid #4a4a4a;
        */
        background-color: rgb(248, 148, 6);
        color: white;
        border: 1px solid white;
        border-radius: 4px;
        width: 30px;
        text-align: center;
    }

    .datatable-image-wrapper .gallery-img-buttons .gallery-img-btn:hover {
        font-size: 36px;
    }

    .datatable-image-wrapper .gallery-img-buttons .gallery-img-btn > i {
        padding-left: 7px;
        padding-right: 7px;
        /*width: 38px;*/
    }

</style>

<style scoped>
    thead {
        display: none;
    }
</style>

<script>
    export default {
        props: {
            trans: {
                type: Object
            },
            ajaxUrl: {
                type: String
            },
            searchFields: { 
                type: Object,
                default: {}
            },
            tableHead: { 
                type: String,
                default: `<tr>
                              <th>image</th>
                          </tr>`
            },
            processing: {
                type: Boolean,
                default: true 
            },
            responsive: {
                type: Boolean,
                default: true 
            },
            searching: {
                type: Boolean,
                default: false 
            },
            order: {
                type: Array,
                default: function() {
                    return [[0, "asc"]]
                }
            },
            initialThumbName: { 
                type: String,
                default: 'Preview'
            },
            thumbSizesData: {
                type: Array
            },
            thumbSizeIdStorageKey: {
                type: String
            },
            thumbSizeNameStorageKey: {
                type: String
            }
        },
        data: function() {
            return {
                "table": null,
                "buttons_data": []
            }
        },
        computed: {

        },
        mounted() {
            // kreiraj 'datatable buttons create array' 
            _.forEach(this.thumbSizesData, (item, key) => {
                //if(item.admin_crop) { <- Dimke kaze da se prikazu sve dimenzije
                    this.buttons_data.push({
                        "text": item.name,
                        "action": ( e, dt, node, config ) => {
                            // Izmeni ime 'button'-a i emituj velicinu ('thumb size')
                            //console.log("Set '"+item.size+"'");
                            this.changeButtonCollectionName(item.name);
                            this.$emit('thumb-size-changed', item.id);
                            localStorage.setItem(this.thumbSizeIdStorageKey, item.id);
                            localStorage.setItem(this.thumbSizeNameStorageKey, item.name);
                        } 
                    });
                //}
            });

            this.initDatatable();

            // edit click
            $('#search_tab_datatable').on('click','[data-photo-action="edit"]', (e) => {
                this.$emit('edit', this.createImageObjFromImagePartial(e));
            });

            // show click
            $('#search_tab_datatable').on('dblclick','[data-photo-action="show"]', (e) => {
                this.$emit('show', this.createImageObjFromImagePartial(e));
            });

            // delete click - pokazi modal
            let deleteOptions = {
                "liveSelector": '[data-photo-action="delete"]'
            };
            $('#search_tab_datatable').questionPop(deleteOptions).on('success.qp', '[data-photo-action="delete"]', (e) => {
                console.log("Delete success");
                this.performDatatableUpdate(false);
                this.$emit('deleted');
            });

        },
        methods: {
            createImageObjFromImagePartial(e) {
                let imageDSM = e.target.closest('.datatable-image-wrapper').dataset;
                // izvrsi konverziju iz DOMStringMap u Object.
                let imageObj = {};
                Object.keys(imageDSM).forEach(k => { imageObj[k] = imageDSM[k]; });
                imageObj['photoTagsIds'] = JSON.parse(imageObj['photoTagsIds']);
                imageObj['photoAllImgSources'] = JSON.parse(imageObj['photoAllImgSources']);
                return imageObj;
            },
            performDatatableUpdate(resetPaging) {
                /*
                STARO - GDE SE POTPUNO UNISTAVA DATATABLES OBJEKAT I KREIRA NOVI
                var self = this;
                this.table.fnDestroy();
                $(self.$el.tBodies[0]).empty();
                this.initDatatable();
                */

                if(typeof resetPaging === 'undefined') {
                    // po 'default'-u resetuj 'paging'
                    resetPaging = true;
                }

                this.$nextTick(function() { // mora 'nextTick' jer bez toga pri selektovanju 'categories buttion collection' dogadjaj kasni za 1 korak!
                    this.table.ajax.reload(() => null, resetPaging );
                    //this.table.draw(); <- NIKAKO, RESETUJE 'PAGING' !!!!
                    this.$emit('update', null);
                });
            },
            changeButtonCollectionName(name) {
                let el = $('.datatable-toolbar .dt-buttons button.buttons-collection');
                el.text(name);
            },
            initDatatable() {
                var self = this;
                let lmSuffix = self.trans.lmSuffix;

                self.table = $(self.$el).DataTable({
                    "processing": self.processing,
                    "responsive": self.responsive,
                    "searching": self.searching,
                    "serverSide": true,
                    "deferLoading": 0,
                    "ajax": {
                        url: self.ajaxUrl,
                        type: "post",
                        data: (d) => {
                            return _.assign(d, this.searchFields);
                        } 
                    },
                    "columns": [
                        {
                            data: "image", 
                            name: "image",
                            render: function ( data, type, row, meta ) {
                                //return '<div class="no-vue">'+data+'</div>' <- ovde npr. ovako moze da se ekstenduje 'template'.
                                return data;
                            }
                        }
                    ],
                    "order": self.order,
                    "initComplete": function(settings, json) {
                        self.$emit('create', json);
                    },
                    "pagingType": "full_numbers",
                    "scrollY": "645px", 
                    "scrollCollapse": true,
                    "lengthMenu": [[8, 12, 24, 50, 100], [8, 12, 24, 50, 100].map((el) => el + ' ' + lmSuffix)],
                    "language": {
                        "sZeroRecords": self.trans.zeroRecords,
                        "lengthMenu": "_MENU_",
                        /*
                        Izmena HTML-a
                        "lengthMenu": 'Display <select>'+
                            '<option value="10">8</option>'+
                            '<option value="20">12</option>'+
                            '<option value="30">24</option>'+
                            '<option value="40">50</option>'+
                            '<option value="50">100</option>'+
                            '</select> records'
                        */
                    },
                    //"sDom": '<"top"i>rt<"bottom"flp><"clear">'
                    "dom": '<"datatable-toolbar"Bflp><"top">rt<"bottom"><"clear">',
                    "buttons": [
                        {
                            extend: 'collection',
                            text: this.initialThumbName,
                            autoClose: true,
                            fade: 0,
                            buttons: this.buttons_data
                        }
                    ]
                });

                // setuj kolicinu(broj) "page button"-a "datatable paging"-a
                $.fn.DataTable.ext.pager.numbers_length = 5;

                return self.table;
            }
        }
    }
</script>