import React from 'react';
import {MdWidgets} from 'react-icons/md';
import posed from 'react-pose';

import Loading from "../../../component/Loading";

import SchemaEditor from "../../../component/Schema/EditorLoader";

import {withTheme, injectSheet} from '../../../lib/theme';
import selectByDot from '../../../lib/selectByDot';
import {ApiRequest, GET} from "../../../lib/ApiRequest";

import {SaveSingle} from '../../../component/ContentStore';
import {blockName} from "../BlockName";

const styling = theme => ({
    wrapper: {
        overflow: 'hidden',
    }
});

const Wrapper = posed.div({
    hidden: {
        height: 0,
        paddingBottom: 0,
    },
    visible: {
        height: 'auto',
        paddingBottom: '3px',
    }
});


const initialState = {
    block: {},
    title: false,
    loaded: false,
    hasSchema: false
};

class ContentBlock extends React.Component {

    state = initialState;

    constructor(props) {
        super(props);

        this.saveEvt = new SaveSingle();
    }

    componentWillUnmount() {
        this.setState(initialState);

        this.props.data.rmSave(this.props.root_name, this.props.index);

        if(this.props.rmSave) {
            this.props.rmSave(this.props.data.id);
        }
    }

    //
    // Api Fetch and Push

    fetch(block) {
        this.setState({loaded: 'progress'});
        (new ApiRequest('api', GET, 'content/block/' + block))
            .debug(true)
            .header({})
            .exec()
            .then((res) => {
                if(res && res.data) {
                    //
                    let title = false;
                    if(res.data.schema && res.data.schema.title) {
                        title = selectByDot(res.data.schema.title, this.props.data.data);
                        if('string' === typeof title) {
                            let tmp_title = document.createElement('DIV');
                            tmp_title.innerHTML = title;
                            title = tmp_title.textContent || tmp_title.innerText || "";

                            if(50 < title.length) {
                                title = title.substr(0, 50) + '...';
                            }
                        }
                    }

                    this.setState({
                        block: res.data,
                        title: title,
                        loaded: true,
                        hasSchema: (!!res.data.schema)
                    });

                    this.props.data.addSave(this.props.root_name, this.props.index, this.saveEvt.trigger);
                } else {
                    this.setState({
                        loaded: 'error'
                    });
                }
            })
            .catch(() => {
                this.setState({
                    loaded: 'error'
                });
            });
    }

    componentDidUpdate(prevProps) {
        if(
            prevProps.data !== this.props.data &&
            this.props.data.id
        ) {
            this.props.data.rmSave(prevProps.root_name, prevProps.index);
            this.fetch(this.props.data.id);
        }
    }

    componentDidMount() {
        if(this.props.data.id) {
            this.fetch(this.props.data.id);
        }
    }

    render() {
        const {data, t, classes, head, deleteItem, onToggle, open} = this.props;
        const {addSave, rmSave} = this.saveEvt;
        const Hd = head;

        return (
            <React.Fragment>
                <Hd
                    icon={(p) => <MdWidgets size={'1.875em'} {...p}/>}
                    lbl={(p) => (
                        <React.Fragment>
                            {blockName(data.id, t)}
                            {this.state.title ? <span style={{marginLeft: '3px', fontStyle: 'italic'}}>· {this.state.title}</span> : null}
                        </React.Fragment>
                    )}
                    deleteItem={deleteItem}
                    onEdit={onToggle}
                    showEdit={this.state.hasSchema}
                    loading={'progress' === this.state.loaded}
                    isEditOpen={open}
                />

                <Wrapper className={classes.wrapper} withParent={false} pose={open ? 'visible' : 'hidden'}>

                    {('progress' === this.state.loaded || 'error' === this.state.loaded ?
                        <Loading
                            style={{
                                wrapper: {margin: 0},
                            }}
                            errorWarning={'error' === this.state.loaded}
                        /> :
                        null)}

                    {this.state.block && this.state.block.schema ?
                        <SchemaEditor data={this.props.data.data}
                                      schema={this.state.block.schema}
                                      addSave={addSave}
                                      rmSave={rmSave}
                                      cacheid={this.props.uid}
                                      tScope={'doc-tree.block.' + data.id}
                        /> :
                        t('no-editable-meta')
                    }
                </Wrapper>
            </React.Fragment>
        )
    };
}

export default withTheme(injectSheet(styling)(ContentBlock));