import React, {Component} from 'react';
import PropTypes from 'prop-types';
import ReactCropper from 'react-cropper';
import Popup from '../Popup';
import {observer} from 'mobx-react/index';
import './styles.scss';

function cropperWrapper(cropper, store) {
    return (
        <Popup
            title="Crop Image"
            isBlackOverlay
            isVisible={store.isVisible}
            content={cropper}
            buttons={[
                {
                    title: 'Crop image',
                    isPrimary: true,
                    promise: () => store.onCropPromise(),
                },
            ]}
            closePromise={() => store.hideCropper()}
        />
    );
}

@observer
class Cropper extends Component {
    render() {
        if (!this.props.store.isVisible) {
            return null;
        }

        const state = this.props.store.cropperState;

        const cropper = (
            <ReactCropper
                ref={(node) => { this.props.store.setCropper(node); }}
                src={state.preview}
                style={{
                    width: state.width,
                }}
                aspectRatio={state.aspectRatio}
                guides={false}
            />
        );

        return (
            cropperWrapper(cropper, this.props.store)
        );
    }
}

Cropper.propTypes = {
    store: PropTypes.object.isRequired,
};

export default Cropper;
