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

export default class Controller extends Section {
    $onInit() {
        this.refresh();
    }

    refresh() {
        let filter = {
            where: {account: this.$params.id},
            include: {
                relation: 'alias',
                scope: {
                    fields: ['id', 'alias', 'description']
                }
            }
        };
        return this.$http.get(`MailAliasAccounts`, {filter})
            .then(res => this.$.data = res.data);
    }

    onAddClick() {
        this.addData = {account: this.$params.id};
        this.$.dialog.show();
    }

    onAddSave() {
        return this.$http.post(`MailAliasAccounts`, this.addData)
            .then(() => this.refresh())
            .then(() => this.vnApp.showSuccess(
                this.$t('Subscribed to alias!'))
            );
    }

    onRemove(row) {
        return this.$http.delete(`MailAliasAccounts/${row.id}`)
            .then(() => {
                this.$.data.splice(this.$.data.indexOf(row), 1);
                this.vnApp.showSuccess(this.$t('Unsubscribed from alias!'));
            });
    }
}

ngModule.component('vnUserAliases', {
    template: require('./index.html'),
    controller: Controller,
    require: {
        card: '^vnUserCard'
    }
});