import React from 'react';
import PureRenderMixin from 'react-addons-pure-render-mixin';

import ConfigStore from 'stores/Config';
import SettingsActions from 'actions/Settings';

import BunkerStore from 'stores/Bunker';
import SettingsStore from 'stores/Settings';

import StoreMixin from 'lib/StoreMixin';
import Url from 'lib/Url';
import Metrika from 'lib/metrika';
import PinnedNotification from './index';

function getSettingsKey(id) {
    return `custom_survey_status_${id}`;
}

const CustomSurvey = React.createClass({
    mixins: [StoreMixin, PureRenderMixin],

    getStoreState() {
        return {
            survey: BunkerStore.getNode('survey'),
        };
    },

    componentDidMount() {
        this.subscribe([BunkerStore]);
    },

    _shouldRender() {
        const { survey } = this.state;

        return survey && survey.isEnabled && !SettingsStore.get(getSettingsKey(survey.id));
    },

    _onConfirm() {
        const tld = ConfigStore.get('app.tld');
        const { survey } = this.state;

        Url.open(survey.url[tld], '_blank');

        Metrika.send('Блок для опросов', survey.id);

        return SettingsActions.updateSettings({
            [getSettingsKey(survey.id)]: 'opened',
        });
    },

    _onCancel() {
        return SettingsActions.updateSettings({
            [getSettingsKey(this.state.survey.id)]: 'canceled',
        });
    },

    render() {
        const { survey } = this.state;
        const locale = ConfigStore.get('app.locale');

        if (!this._shouldRender()) {
            return null;
        }

        return (
            <PinnedNotification
                content={survey.text[locale]}
                confirmButtonText={survey.button[locale]}
                onConfirm={this._onConfirm}
                onCancel={this._onCancel}
            />
        );
    },

});

export default CustomSurvey;
