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

class Controller extends Section {
    constructor($element, $, vnEmail) {
        super($element, $);
        this.vnEmail = vnEmail;
    }

    get client() {
        return this._client;
    }

    set client(value) {
        this._client = value;

        if (value) {
            this.setClientSample(value);
            this.clientAddressesList(value.id);
        }
    }

    get companyId() {
        if (!this.clientSample.companyFk)
            this.clientSample.companyFk = this.vnConfig.companyFk;
        return this.clientSample.companyFk;
    }

    set companyId(value) {
        this.clientSample.companyFk = value;
    }

    get addressId() {
        if (!this.clientSample.addressId)
            this.clientSample.addressId = this.client.defaultAddressFk;
        return this.clientSample.addressId;
    }

    set addressId(value) {
        this.clientSample.addressId = value;
    }

    onSubmit() {
        this.$.watcher.check();

        const validationMessage = this.validate();
        if (validationMessage)
            return this.vnApp.showError(this.$t(validationMessage));

        this.$.watcher.realSubmit().then(() => this.send());
    }

    validate() {
        const sampleType = this.$.sampleType.selection;

        if (!this.clientSample.recipient)
            return 'Email cannot be blank';

        if (!sampleType)
            return 'Choose a sample';

        if (sampleType.hasCompany && !this.clientSample.companyFk)
            return 'Choose a company';

        if (sampleType.datepickerEnabled && !this.clientSample.from)
            return 'Choose a date';

        return;
    }

    setParams(params) {
        const sampleType = this.$.sampleType.selection;

        if (sampleType.hasCompany)
            params.companyId = this.clientSample.companyFk;

        if (sampleType.datepickerEnabled)
            params.from = this.clientSample.from;

        if (this.clientSample.addressId)
            params.addressId = this.clientSample.addressId;
    }

    preview() {
        const sampleType = this.$.sampleType.selection;

        const params = {
            recipientId: this.$params.id
        };

        const validationMessage = this.validate();
        if (validationMessage)
            return this.vnApp.showError(this.$t(validationMessage));

        this.setParams(params);

        const path = `${sampleType.model}/${this.$params.id}/${sampleType.code}-html`;
        this.$http.get(path, {params})
            .then(response => {
                this.$.showPreview.show();
                const dialog = document.body.querySelector('div.vn-dialog');
                const body = dialog.querySelector('tpl-body');
                const scroll = dialog.querySelector('div:first-child');

                body.innerHTML = response.data;
                scroll.scrollTop = 0;
            });
    }

    send() {
        const sampleType = this.$.sampleType.selection;

        const params = {
            recipientId: this.client.id,
            recipient: this.clientSample.recipient,
            replyTo: this.clientSample.replyTo
        };

        const validationMessage = this.validate();
        if (validationMessage)
            return this.vnApp.showError(this.$t(validationMessage));

        this.setParams(params);

        const path = `${sampleType.model}/${this.$params.id}/${sampleType.code}-email`;
        this.vnEmail.send(path, params)
            .then(() => this.$state.go('client.card.sample.index'));
    }

    setClientSample(client) {
        const userId = window.localStorage.currentUserWorkerId;
        const params = {filter: {where: {userFk: userId}}};
        this.$http.get('EmailUsers', params).then(res => {
            const [worker] = res && res.data;
            this.clientSample = {
                clientFk: this.$params.id,
                companyId: this.vnConfig.companyFk,
                recipient: client.email,
                replyTo: worker.email
            };
        });
    }

    clientAddressesList(value) {
        let filter = {
            include: [
                {
                    relation: 'province',
                    scope: {
                        fields: ['name']
                    }
                },
                {
                    relation: 'agencyMode',
                    scope: {
                        fields: ['name']
                    }
                }
            ]
        };
        filter = encodeURIComponent(JSON.stringify(filter));

        let query = `Clients/${value}/addresses?filter=${filter}`;
        this.$http.get(query).then(res => {
            if (res.data)
                this.addresses = res.data;
        });
    }

    getClientDefaultAddress(value) {
        let query = `Clients/${value}`;
        this.$http.get(query).then(res => {
            if (res.data)
                this.addressId = res.data.defaultAddressFk;
        });
    }
}

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

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