import ngModule from '../module';
import Section from 'salix/components/section';
import UserError from 'core/lib/user-error';

class Controller extends Section {
    constructor($element, $, vnFile) {
        super($element, $, vnFile);
        this.dms = {
            files: [],
            hasFile: false,
            hasFileAttached: false
        };
        this.vnFile = vnFile;
        this.getAllowedContentTypes();
        this._editDownloadDisabled = false;
    }

    get contentTypesInfo() {
        return this.$t('ContentTypesInfo', {
            allowedContentTypes: this.allowedContentTypes
        });
    }

    get editDownloadDisabled() {
        return this._editDownloadDisabled;
    }

    async checkFileExists(dmsId) {
        if (!dmsId) return;
        let filter = {
            fields: ['id']
        };
        await this.$http.get(`Dms/${dmsId}`, {filter})
            .then(() => this._editDownloadDisabled = false)
            .catch(() => this._editDownloadDisabled = true);
    }

    async getFile(dmsId) {
        const path = `Dms/${dmsId}`;
        await this.$http.get(path).then(res => {
            const dms = res.data && res.data;
            this.dms = {
                dmsId: dms.id,
                reference: dms.reference,
                warehouseId: dms.warehouseFk,
                companyId: dms.companyFk,
                dmsTypeId: dms.dmsTypeFk,
                description: dms.description,
                hasFile: dms.hasFile,
                hasFileAttached: false,
                files: []
            };
        });
    }

    getAllowedContentTypes() {
        this.$http.get('DmsContainers/allowedContentTypes').then(res => {
            if (res.data.length > 0) {
                const contentTypes = res.data.join(', ');
                this.allowedContentTypes = contentTypes;
            }
        });
    }

    openEditDialog(dmsId) {
        this.getFile(dmsId).then(() => this.$.dmsEditDialog.show());
    }

    openCreateDialog() {
        const params = {filter: {
            where: {code: 'invoiceIn'}
        }};
        this.$http.get('DmsTypes/findOne', {params}).then(res => {
            this.dms = {
                reference: this.invoiceIn.supplierRef,
                warehouseId: this.vnConfig.warehouseFk,
                companyId: this.vnConfig.companyFk,
                dmsTypeId: res.data.id,
                description: this.invoiceIn.supplier.name,
                hasFile: true,
                hasFileAttached: true,
                files: null
            };
            this.$.dmsCreateDialog.show();
        });
    }

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

    onFileChange(files) {
        let hasFileAttached = false;
        if (files.length > 0)
            hasFileAttached = true;

        this.$.$applyAsync(() => {
            this.dms.hasFileAttached = hasFileAttached;
        });
    }

    onEdit() {
        if (!this.dms.companyId)
            throw new UserError(`The company can't be empty`);
        if (!this.dms.warehouseId)
            throw new UserError(`The warehouse can't be empty`);
        if (!this.dms.dmsTypeId)
            throw new UserError(`The DMS Type can't be empty`);
        if (!this.dms.description)
            throw new UserError(`The description can't be empty`);

        const query = `dms/${this.dms.dmsId}/updateFile`;
        const options = {
            method: 'POST',
            url: query,
            params: this.dms,
            headers: {
                'Content-Type': undefined
            },
            transformRequest: files => {
                const formData = new FormData();

                for (let i = 0; i < files.length; i++)
                    formData.append(files[i].name, files[i]);

                return formData;
            },
            data: this.dms.files
        };

        this.$http(options).then(res => {
            if (res) {
                this.vnApp.showSuccess(this.$t('Data saved!'));
                if (res.data.length > 0) this.invoiceIn.dmsFk = res.data[0].id;
            }
        });
    }

    onCreate() {
        if (!this.dms.companyId)
            throw new UserError(`The company can't be empty`);
        if (!this.dms.warehouseId)
            throw new UserError(`The warehouse can't be empty`);
        if (!this.dms.dmsTypeId)
            throw new UserError(`The DMS Type can't be empty`);
        if (!this.dms.description)
            throw new UserError(`The description can't be empty`);
        if (!this.dms.files)
            throw new UserError(`The files can't be empty`);

        const query = `Dms/uploadFile`;
        const options = {
            method: 'POST',
            url: query,
            params: this.dms,
            headers: {
                'Content-Type': undefined
            },
            transformRequest: files => {
                const formData = new FormData();

                for (let i = 0; i < files.length; i++)
                    formData.append(files[i].name, files[i]);

                return formData;
            },
            data: this.dms.files
        };

        this.$http(options).then(res => {
            if (res) {
                this.vnApp.showSuccess(this.$t('Data saved!'));
                if (res.data.length > 0) this.invoiceIn.dmsFk = res.data[0].id;
            }
        });
    }
}

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

ngModule.vnComponent('vnInvoiceInBasicData', {
    template: require('./index.html'),
    controller: Controller,
    bindings: {
        invoiceIn: '<'
    }
});