import ngModule from '../../module';
import Section from 'salix/components/section';
import './style.scss';

class Controller extends Section {
    constructor($element, $, vnFile) {
        super($element, $);
        this.vnFile = vnFile;
        this.filter = {
            include: {
                relation: 'dms',
                scope: {
                    fields: [
                        'dmsTypeFk',
                        'workerFk',
                        'hardCopyNumber',
                        'reference',
                        'description',
                        'hasFile',
                        'file',
                        'created',
                    ],
                    include: [{
                        relation: 'dmsType',
                        scope: {
                            fields: ['name']
                        }
                    },
                    {
                        relation: 'worker',
                        scope: {
                            fields: ['userFk'],
                            include: {
                                relation: 'user',
                                scope: {
                                    fields: ['name']
                                }
                            },
                        }
                    }]
                },
            }
        };
    }

    deleteDms(index) {
        const dmsFk = this.ticketDms[index].dmsFk;
        this.$http.post(`ticketDms/${dmsFk}/removeFile`)
            .then(() => {
                this.$.model.remove(index);
                this.vnApp.showSuccess(this.$t('Data saved!'));
            });
    }

    downloadFile(dmsId) {
        this.vnFile.download(`api/dms/${dmsId}/downloadFile`);
    }

    importDms() {
        try {
            if (!this.dmsId)
                throw new Error(`The document indentifier can't be empty`);

            const data = {
                ticketFk: this.$params.id,
                dmsFk: this.dmsId
            };

            this.$http.post('ticketDms', data).then(() => {
                this.vnApp.showSuccess(this.$t('Data saved!'));
                this.dmsId = null;
                this.$.model.refresh();
            });
        } catch (e) {
            this.vnApp.showError(this.$t(e.message));
            return false;
        }
        return true;
    }
}

Controller.$inject = ['$element', '$scope', 'vnFile'];

ngModule.vnComponent('vnTicketDmsIndex', {
    template: require('./index.html'),
    controller: Controller,
});