import React, { Component } from "react";
import PropTypes from 'prop-types';

import { injectIntl } from 'react-intl';

import { 
        AbstractForm, 
        ActivityIndicator, 
        Toolbar, 
        ToolbarSection, 
        ToolbarButton, 
        ToolbarButtons, 
        ToolbarRow, 
        ListTitle,
        PortalContainer } from 'lib/components';

import Toast from 'components/Toast';

import backendRequest from 'lib/backend';
import { fromJS } from 'immutable';
import icons from 'constants/icons';
import form from 'lib/form';
import validator from 'lib/validator';

import messages from './messages.js';
import commonMessages from '../../../messages.js';


class PasswordForm extends AbstractForm {

    constructor(props) {
        super(props);

        this.handleBack = this.handleBack.bind(this);
        this.handleSave = this.handleSave.bind(this);
    }

    handleBack() {
        this.context.router.push('/settings');
    }


    async handleSave(data) {
        let intl = this.props.intl;

        let unitId = global.cfg.unitId;
        try {
            await backendRequest(`/api/${unitId}/settings/password`, "PUT", { body: data });  
            Toast.saved();
            this.handleBack();
        } catch (e) {
            Toast.error(e);
        }
    }


    render() {
        let { status, intl, submit } = this.props;
        let pending = !!(status && ( status.isFetching || status.isSaving ));
        let formProps = { type: "password" };

        return (
            <div className="pv10">
                <Toolbar>
                    <ToolbarSection>
                        <ListTitle 
                            title={ intl.formatMessage(messages.title) }
                            titleIcon={ icons.passwordSettings }
                            />
                    </ToolbarSection>
                    <ToolbarButtons>
                        <ToolbarButton 
                            label={ intl.formatMessage(commonMessages.buttonBack) }
                            onClick={ this.handleBack } 
                            >
                            <span className="icon">{ icons.back }</span>
                        </ToolbarButton>
                        <ToolbarButton 
                            label={ intl.formatMessage(commonMessages.buttonSave) }
                            onClick={ () => submit(this.handleSave) } 
                            >
                            <span className="icon">{ icons.save }</span>
                        </ToolbarButton>
                    </ToolbarButtons>
                </Toolbar>

                <PortalContainer>
                    <div>
                        <div className="form">
                            { this.renderField("currentPassword", intl.formatMessage(messages.currentPassword), formProps) }
                            { this.renderField("newPassword", intl.formatMessage(messages.newPassword), formProps) }
                            { this.renderField("newPasswordCheck", intl.formatMessage(messages.retypePassword), formProps) }
                        </div>
                    </div>
                </PortalContainer>

                <ActivityIndicator show={ pending } type="overlay" />
            </div>
        );
    }

}


PasswordForm.contextTypes = {
    router: PropTypes.object.isRequired
};

export default injectIntl(form(PasswordForm, {
    onValidationFailed: Toast.validationFailed,
    validate: (unit, error) => {
        let valid = true;
        if (!validator.required(unit.currentPassword)) {
            error({ field: "currentPassword", code: "common.validation.requiredField" });
            valid = false;
        }
        if (!validator.required(unit.newPassword)) {
            error({ field: "newPassword", code: "common.validation.requiredField" });
            valid = false;
        }
        if (!validator.required(unit.newPasswordCheck)) {
            error({ field: "newPasswordCheck", code: "common.validation.requiredField" });
            valid = false;
        }
        return valid;
    }
}));
