'use strict';

/**
 * Страница
 * @module gift-page
 * @extends i-bem__dom
 * @author ertema
 */
BEM.DOM.decl('gift-page', {
    onSetMod: {
        js: function() {
            this._prepareInfo();
            this._prepareGift();
        }
    },
    _renderGift: function(data) {
        BEM.DOM.update(this.elem('gift'), BEMHTML.apply({
            block: 'gift',
            data: data
        }));
        this._initForm();
    },
    _initRefreshButton: function() {
        var refreshButton = this.findBlockInside('gift').findBlockOn('button-refresh', 'button2');

        if (refreshButton) {
            refreshButton.on('click', function() {
                this._prepareInfo();
                this._prepareGift();
            }, this);
        }
    },
    _initForm: function() {
        var form = this.findBlockInside('s-form');

        if (form) {
            form.on('success', function(event, data) {
                this._renderGift(data.response);
            }, this);
        }
    },
    _prepareGift: function() {
        $.ajax('/api/' + location.pathname.split('/')[1] + '/prepare/', {
            xhrFields: {
                withCredentials: true
            }
        })
            .then(function(data) {
                this._renderGift(data);
            }.bind(this))
            .fail(function(error) {
                console.error('fail', error);
                this._renderGift(error);
                this._initRefreshButton();
            }.bind(this));
    },
    _prepareInfo: function() {
        $.ajax('/api/' + location.pathname.split('/')[1] + '/info/', {
            xhrFields: {
                withCredentials: true
            }
        })
            .then(function(data) {
                this._renderInfo(data.comment);
            }.bind(this))
            .fail(function(error) {
                console.error('fail', error);
                BEM.DOM.update(this.elem('info'), 'Не удалось загрузить описание раздачи');
            }.bind(this));
    },
    _renderInfo: function(description) {
        BEM.DOM.update(
            this.elem('info'),
            BEMHTML.apply(BEM.blocks['i-common__string'].escapeHTML(description))
        );
    }
});
