import _ from 'lodash';
import { Permissions } from 'constants/Common';
import submit from 'services/submit';
import { i18n } from 'lib/i18n';
import Url from 'lib/Url';
import timer from 'lib/timer';

import AuthStore from 'stores/Auth';
import PermissionStore from 'stores/Permissions';
import ModalActions from 'actions/Modal';
import UserActions from 'actions/User';
import UserStore from 'stores/Users';
import UserForm from 'components/User/Forms/Create';

export default {
    create,
    dismiss,
};

function create(props) {
    let isSubmitted;

    timer.start('create_user');

    ModalActions.open({
        title: i18n('department.new_user'),
        component: UserForm,
        props: {
            departmentId: props.department,
            redirect: props.redirect,
            onSubmit(data) {
                isSubmitted = true;
                ModalActions.close();

                if (props.onSubmit) {
                    props.onSubmit(data);
                }
            },
            onCancel() {
                timer.clear('create_user');
                ModalActions.close();
            },
        },
        onClose() {
            if (!isSubmitted) {
                timer.clear('create_user');
            }
        },
    });
}

function dismiss(id) {
    // удаляемый пользователь - текущий пользователь и владелец организации
    if (AuthStore.getUserId() === id && PermissionStore.contains(Permissions.CHANGE_OWNER)) {
        return ModalActions.confirm({
            message: i18n('user.message.cannot_dismiss_owner.current_user'),
            confirmButtonText: i18n('user.action.to_org_profile'),
            onConfirm() {
                Url.open(Url.getPath('/admin/profile'));
            },
        });
    }

    UserActions.hasPaidDiskSpace(id).then(value => {
        const key = value ? 'paid_disk' : 'ordinary';

        ModalActions.confirm({
            message: i18n(`user.message.confirm_dismissal.${key}`, {
                user: _.escape(UserStore.getName(id)),
            }),
            confirmButtonText: i18n('user.action.dismiss'),
            onConfirm() {
                submit(UserActions.dismissUser(id), {
                    success: i18n('user.status.dismissed'),
                    failure: i18n('user.status.failed_to_dismiss'),
                });
            },
        });
    });
}
