import { fetchWithErrorHandling } from '@neos-project/neos-ui-backend-connector';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { $get, $transform } from 'plow-js';
import { Button } from '@neos-project/react-ui-components';
import { connect } from 'react-redux';
import { actions } from '@neos-project/neos-ui-redux-store';
import { neos } from '@neos-project/neos-ui-decorators';

@neos((globalRegistry) => ({
    i18nRegistry: globalRegistry.get('i18n'),
}))
@connect(
    $transform({
        documentNodeContextPath: $get('cr.nodes.documentNode'),
    }),
    {
        addFlashMessage: actions.UI.FlashMessages.add,
    },
)
export default class PageCacheView extends Component {
    static propTypes = {
        documentNodeContextPath: PropTypes.string.isRequired,
        addFlashMessage: PropTypes.func.isRequired,
    };

    clearCache = async(documentNodeContextPath) => {
        try {
            const response = await fetchWithErrorHandling.withCsrfToken(csrfToken => ({
                url: '/api/cache/clear-page-cache',

                method: 'POST',
                credentials: 'include',
                headers: {
                    'X-Flow-Csrftoken': csrfToken,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ node: documentNodeContextPath }),
            }));

            if (!response.ok) {
                throw new Error('Ooooops. Something went wrong.');
            }

            this.props.addFlashMessage(
                'pageCacheSuccess',
                this.props.i18nRegistry.translate('Newland.Toubiz.Sync.Neos:NodeTypes.PageCacheMixin:clearPageCacheSuccess'),
                'success',
                5000,
            );
        } catch (error) {
            this.props.addFlashMessage(
                'pageCacheError',
                this.props.i18nRegistry.translate('Newland.Toubiz.Sync.Neos:NodeTypes.PageCacheMixin:clearPageCacheError'),
                'error',
                5000,
            );
            console.error(error.message);
        }
    };

    render() {
        return <div>
            <Button style="lighter" onClick={() => this.clearCache(this.props.documentNodeContextPath)}>
                {this.props.i18nRegistry.translate('Newland.Toubiz.Sync.Neos:Cache:clearCache')}
            </Button>
        </div>;
    }
}

export const PageCacheContainer = neos((globalRegistry) => ({
    options: globalRegistry
        .get('Newland.Toubiz.Sync.Neos.PageCacheButton'),
}))(PageCacheView);
