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

class Controller extends Section {
    constructor($element, $) {
        super($element, $);
        const filter = {
            where: {userFk: this.$params.id},
            include: {relation: 'deviceProduction'}
        };
        this.$http.get('DeviceProductionUsers', {filter}).
            then(res => {
                if (res.data && res.data.length > 0)
                    this.setCurrentPDA(res.data[0]);
            });
    }

    deallocatePDA() {
        this.$http.post(`Workers/${this.$params.id}/deallocatePDA`, {pda: this.currentPDA.deviceProductionFk})
            .then(() => {
                this.vnApp.showSuccess(this.$t('PDA deallocated'));
                delete this.currentPDA;
            });
    }

    allocatePDA() {
        this.$http.post(`Workers/${this.$params.id}/allocatePDA`, {pda: this.newPDA})
            .then(res => {
                if (res.data)
                    this.setCurrentPDA(res.data);

                this.vnApp.showSuccess(this.$t('PDA allocated'));
                delete this.newPDA;
            });
    }

    setCurrentPDA(data) {
        this.currentPDA = data;
        this.currentPDA.description = [];
        this.currentPDA.description.push(`ID: ${this.currentPDA.deviceProductionFk}`);
        this.currentPDA.description.push(`${this.$t('Model')}: ${this.currentPDA.deviceProduction.modelFk}`);
        this.currentPDA.description.push(`${this.$t('Serial Number')}: ${this.currentPDA.deviceProduction.serialNumber}`);
        this.currentPDA.description = this.currentPDA.description.join(' ');
    }
}

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

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