import React from 'react';
import Trix from 'trix';
import addClass from 'reneco-utils/addClass';
import sendFile from 'reneco-utils/sendFile';

import './Editor.sass';
import 'trix/dist/trix.css';

let counter = 0;

export default class TrixEditor extends React.Component {
    static defaultProps = {
        fileTypes: ['image/jpeg', 'image/png', 'image/gif'],
        maxFileSize: 2097152, // 2mb
        defaultPlaceholder: ''
    }
    ix = 'trix-editor-'+counter++;

    onChange = () => {
        this.props.onChange && this.props.onChange(this.Input.value);
    }

    attachAdd = e => {
        let attachment = e.attachment,
            props = this.props;
        if (props.uploadUrl && attachment.file) {
            // this.Trix.composition.updateAttributesForAttachment({
            //     caption: props.defaultPlaceholder
            // }, attachment);
            return sendFile({
                url: props.uploadUrl,
                file: attachment.file,
                messager: props.messager,
                onProgress: e => {
                    let progress = e.loaded / e.total * 100;
                    return attachment.setUploadProgress(progress);
                },
                onSuccess: response => {
                    props.onImageUpload && props.onImageUpload(response, attachment);
                },
                onError: e => {
                    this.props.onError && this.props.onError([e.message]);
                    // need to remove Attache from trix editor
                }
            });
        }
    }
    checkFile = e => {
        let errors = [];
        if(!this.props.uploadUrl) {
            errors.push('file upload is disabled');
        }
        if (this.props.fileTypes.indexOf(e.file.type) < 0) {
            errors.push('files of this type cannot be uploaded');
        }
        if (e.file.size > this.props.maxFileSize) {
            errors.push('file too large (max ' + (this.props.maxFileSize / 1048576) + 'mb)');
        }
        if (errors.length > 0) {
            e.preventDefault();
            this.props.onError && this.props.onError(errors);
        }
    }
    removeFile = e => {
        this.props.onImageRemove && this.props.onImageRemove(e.attachment.attachment.previewURL);
    };
    addTrix() {
        // let buttonHTML = '<button type="button" class="heading" data-attribute="heading" title="Heading">Heading</button>',
        //     groupElement = this.Trix.config.toolbar.content.querySelector('.block_tools');
        // groupElement.insertAdjacentHTML('beforeend', buttonHTML);
    }
    componentDidMount() {
        this.addTrix();
        this.Trix.addEventListener('trix-change', this.onChange);
        this.Trix.addEventListener('trix-file-accept', this.checkFile);
        this.Trix.addEventListener('trix-attachment-add', this.attachAdd);
        this.Trix.addEventListener('trix-attachment-remove', this.removeFile);
    }
    componentWillUnmount() {
        this.Trix.removeEventListener('trix-change', this.onChange);
        this.Trix.removeEventListener('trix-file-accept', this.checkFile);
        this.Trix.removeEventListener('trix-attachment-add', this.attachAdd);
        this.Trix.removeEventListener('trix-attachment-remove', this.removeFile);
    }
    shouldComponentUpdate() {
        return false;
    }
    render() {
        let props = this.props,
            baseClass = 'trix-editor';

        return (<div className={addClass(baseClass, props.className)}>
            {props.title && <label htmlFor={this.ix}>{props.title}</label>}
            <div className={addClass(baseClass + '__textarea-wrapper', props.textareaWrapperClassName)}>
                <input ref={ref=>{this.Input = ref;}} id={this.ix} value={props.value || ''} type='hidden' />
                <Trix ref={ref => { this.Trix = ref; }} input={this.ix}>{props.value}</Trix>
            </div>
        </div>);
    }
}
