Ext.define("App.view.PhotoPanel", {
    extend: "Ext.form.Panel",
    xtype: "photoPanel",
    params: {},
    scrollable: true,
    layout: 'vbox',

    refType: '',
    refId:-1,
    url:'',

    loadPanel: function(id){
        var me = this;
        me.refId = id;
        Ext.Ajax.request({
            url: me.url,
            params: {id: me.refId},
            success: function(response, opts) {
                var result = Ext.decode(response.responseText);
                me.down('#imageContainer').removeAll(true);
                result.records.forEach(function(item, index, array) {
                   me.down('#imageContainer').add({
                       xtype: 'imagefield',
                       name: item.filename,
                       thumbnailPath: App.url("/file/thumbnail/"+item.id+"/"+item.skey+"/"+item.filename),
                       path: App.url("/file/dl/"+item.id+"/"+item.skey+"/"+item.filename),
                       imageWidth: 300,
                       imageHeight: 300,
                       fileId: item.id,
                       skey: item.skey,
                   });
                });

            },
            failure: function(response, opts) {
                App.showError('Message : ' + response.status);
            },
            scope: this
        });
    },
    uploadFiles: function(){
        var me = this;
        if(!me.down('filefield').files) return;

        let xhr = new XMLHttpRequest();
        let fd = new FormData();
        xhr.open('POST',App.url("/file/files/ul")+"?_csrf="+App.csrf , true);
        var fileList = me.down('filefield').files;
        for(var i=0; i<fileList.length; i++){
            fd.append('multipartFiles', fileList[i]);
        }
        fd.append('refType', me.refType);
        fd.append('refId', me.refId);

        xhr.setRequestHeader('serverTimeDiff', 0);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                // handle the answer, in order to detect any server side error
                if (Ext.decode(xhr.responseText).success) {
                    App.showMsg('Document Uploaded');
                    me.loadPanel(me.refId);
                    return true;
                } else if (xhr.readyState == 4 && xhr.status == 404) {
                    App.showMsg('Document Upload Failed');
                    return false;
                }
            }
        };
        // Initiate a multipart/form-data upload
        xhr.send(fd);        
    },
    uploadFile: function(){
        var me = this;
        if(me.down('filefield').getValue()=="") return;

        me.getForm().submit({
            waitMsg: 'Uploading...',
            url:  App.url("/file/ul")+"?_csrf="+App.csrf,
            params:{
                refType: me.refType,
                refId: me.refId
            },
            success: function(f, action) {
                App.showMsg('Uploaded');
                me.down('filefield').setValue("");
                me.loadPanel(me.refId)
            },
            failure: function(f, action) {
                alert('Uploaded failure');
                me.down('filefield').setValue("");
            }
        });
    },

    deleteFile: function(){
        var me = this;
        var deleteRecord = [];
        
        me.down('#imageContainer').items.items
            .forEach(function(item, index, array){
                if(item.selected){
                    deleteRecord.push({
                        fileId: item.fileId,
                        refId: me.refId,
                        refType: me.refType,
                        skey: item.skey,
                    });
                }
            });

        if(deleteRecord.length<=0){
            App.showWarning("Please select image.");
            return;
        } 
        Ext.Ajax.request({
            url: App.url("/file/multi-delete"),
            params: { 
                deleteRecord: Ext.encode(deleteRecord),
            },
            success: function(response, opts) {
                App.showMsg('Deleted');
                me.loadPanel(me.refId);
            },
            failure: function(response, opts) {
                App.showError('Message : ' + response.status);
            },
            scope: this
        });
    },
    /*
    printImage: function(){
        var me = this;
        var selectedFileIds = "";
        me.down('#imageContainer').items.items
            .forEach(function(item, index, array){
                if(item.selected){
                    selectedFileIds = selectedFileIds==""
                    ?item.fileId
                    :selectedFileIds+","+item.fileId;
                }
            });
        window.open( App.url("/report/preview.pdf")+'?fileIds=' + selectedFileIds);
    },
    */
    printImage: function(){
        var me = this;
        var source = [];
        me.down('#imageContainer').items.items
            .forEach(function(item, index, array){
                if(item.selected){
                    source.push(item.path);
                }
            });

        if(source.length<=0){
            App.showWarning("Please select image.");
            return;
        } 
       App.printImage(source);
    },
    doDownload: function(){
		var me = this;
        var ids = [];
        var skeys = [];
        
		me.down('#imageContainer').items.items
            .forEach(function(item){
			if(item.selected){
				ids.push(item.fileId);
				skeys.push(item.skey);
			}
		});
        if(ids.length<=0){
            App.showWarning("Please select image.");
            return;
        } 
		var url = App.url("/file/dlz")+Ext.String.format('?ids={0}&skeys={1}&filename={2}',ids.join(),skeys.join(),"Image");
		window.open(url);
	},
    initComponent: function () {
        var me = this;

        me.uploadButtonId = Ext.id();
        me.uploadlabelId = Ext.id();

        Ext.apply(me, {
            items: [
                {
                    xtype: 'container',
                    layout: 'hbox',
                    width: '100%',
                    margin: '4 0 4 0',
                    defaults:{
                        margin: 4,
                    },
                    items: [
                        {
                            xtype: 'label',
                            html: "<b>"+App.localeRes('Photo')+"</b>",
                            height: '100%',
                        },
                        {
                            xtype: 'container',
                            flex: 1,
                        },
                        {
                            xtype: 'button',
                            text: App.localeRes('Print'),
                            ui: 'soft-purple',
                            iconCls: 'fas fa-print',
                            itemId: 'printBtn',
                            handler: function(button, event){
                               me.printImage();
                            }
                        },
                        {
                            xtype: 'button',
                            text: App.localeRes('Delete'),
                            iconCls: 'fas fa-times-circle',
                            ui: "soft-red",
                            itemId: 'deleteBtn',
                            hidden: !App.isGranted(['FILE_DELETE']),
                            handler: function(button, event){
                                me.deleteFile();
                            }
                        },
                        {
                            xtype: 'filefield',
                            buttonText: App.localeRes('Upload Photo'),
                            buttonConfig:{
                                iconCls: 'fas fa-upload',
                            },
                            ui: 'soft-blue',
                            name: 'multipartFile',
                            itemId: 'photoFileField',
                            submitValue: false,
                            multiple: true,
                            accept: 'image/*',
                            margin: 4,
                            buttonOnly: true,
    
                            listeners: {
                                change: function(field, value, eOpts){
                                    var fileDom = this.getEl().down('input[type=file]');
                                    field.files =  fileDom.dom.files
                                    field.setValue(field.files);
                                    me.uploadFiles();
                                },
                                afterrender:function(cmp){
                                    cmp.fileInputEl.set({
                                        multiple:'multiple'
                                    });
                                }
                            }
                        },
                        {
                            xtype: 'button',
                            text: App.localeRes('Download'),
                            iconCls: 'fas fa-download',
                            ui: "soft-purple",
                            itemId: 'downloadFileBtn',
                            handler: function(button, event){
                                me.doDownload();
                            }
                        },
                    ]
                },
                {
                    xtype: 'container',
                    itemId: 'imageContainer',
                    width: '100%',
                    flex: 1,
                    scrollable: true,
                    layout: {
                        type: 'column',
                    },
                }
            ],
        });

        me.callParent(arguments);

    },
    
});
