import React from 'react';
import PropTypes from "prop-types";

import CollectionAnalysisAPI from '../../api/CollectionAnalysisAPI';
import IDUtil from '../../util/IDUtil';
import FieldSelector from './FieldSelector';
import ComponentUtil from '../../util/ComponentUtil';

//this component relies on the collection statistics as input
class CollectionAnalyser extends React.Component {

	constructor(props) {
		super(props);
        this.STORAGE_PREFIX = 'ms__ca_';

        // throttle preview requests
        // needed because to prevent a large amount of pending requests
        // this keeps the UI / timeline respond fast to changes
        this.calls = [];

        // default values
        const defaultField = window.sessionStorage.getItem(
            this.STORAGE_PREFIX + 'defaultField' + this.props.collectionConfig.collectionId
        ) || '';
		this.state = {
            field : null,
            fields: this.props.collectionConfig.getAllFields(),
            completeness: {}, //store completeness of the fields
            showFieldSelector: false,
            descriptions: null, // field descriptions
		};

    }

    componentDidMount() {
        // auto load the analyse if there are default values
        if (this.state.field){
            this.props.onChange(this.state.field);
        }
        if(this.state.fields) {
            this.loadCompletenessData();
        }
    }

    loadCompletenessData = () => {
        CollectionAnalysisAPI.collectionFieldCompleteness(this.props.collectionConfig.collectionId,
            this.props.collectionConfig.getDocumentType(), (data) => {
            this.setState({fieldCompleteness: data});
            this.props.onCompletenessLoaded(data);
        })
    }

    onShowFieldSelector(){
        this.setState({
            showFieldSelector: !this.state.showFieldSelector
        });
    }

    onFieldSelected(field) {

        // store value to session storage
        window.sessionStorage.setItem(
            this.STORAGE_PREFIX + 'defaultField' + this.props.collectionConfig.collectionId, field.id
        );

        this.setState({
            field: field.id,
            showFieldSelector: false, // hide fieldselector
        });

        this.props.onChange(field.id);
    }

    onCloseFieldSelector() {
        this.setState({
            showFieldSelector: false
        })
    }

    getCurrentField(){
        if (!this.state.field) {
            return null;
        }

        let field = null;
        this.state.fields.some((f)=>{
            if (f.id === this.state.field){
                field = f;
                return true;
            }
            return false;
        });

        return field;
    }

    getFieldDescription(field, collectionMetadata) {
        if(!field || !collectionMetadata || !collectionMetadata.field_descriptions || !collectionMetadata.field_descriptions[field.id]) {
            return null;
        }
        return collectionMetadata.field_descriptions[field.id]['description'];
    }

	render() {
        const collectionMetadata = this.props.collectionConfig.getCollectionMetadata();
		let analysisBlock = null;
        let fieldSelector = null;

		//only draw the rest when a collection is selected (either using the selector or via the props)
		if(this.props.collectionConfig && this.state.fields) {

            // get current field data and completeness
            const field = this.getCurrentField();
            const completeness = field && this.state.fieldCompleteness && field.id in this.state.fieldCompleteness['existCounts'] ? this.state.fieldCompleteness['existCounts'][field.id] : null;
            const description = this.getFieldDescription(field, collectionMetadata);

            // render current field information table
            const currentField = field != null ? (
                <div className="current_field">
                    <table>
                        <tbody>
                            <tr>
                                <th>Field</th><td className="title">{field.title}</td>
                            </tr>
                            <tr>
                                <th>Description</th><td>{description !== null ? description : <i className="fa fa-circle-o-notch fa-spin"/>}</td>
                            </tr>
                            <tr>
                                <th>Type</th><td>{field.type}</td>
                            </tr>
                            <tr>
                                <th>Completeness</th>
                                <td className="completeness">
                                    {completeness ?
                                        <div>
                                            <span>{ComponentUtil.calcCompleteness(completeness, this.state.fieldCompleteness['total'])}%</span>
                                            <span className="total">
                                                {completeness} / {this.state.fieldCompleteness['total']}
                                            </span>
                                        </div>
                                        : <i className="fa fa-circle-o-notch fa-spin"/>
                                    }
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            ) : null;
            // create final analysis block
			analysisBlock = (
				<div className="analysis_field">
                    <button className="btn btn-primary" onClick={this.onShowFieldSelector.bind(this)}>Select field to analyse</button>
                    {currentField}
                </div>
            );
            if (this.state.showFieldSelector) {
                fieldSelector = (
                    <FieldSelector
                        onSelect={this.onFieldSelected.bind(this)}
                        onClose={this.onCloseFieldSelector.bind(this)}
                        selectedField={this.state.field}
                        fields={this.state.fields}
                        completeness={this.state.fieldCompleteness}
                        descriptions={collectionMetadata ? collectionMetadata.field_descriptions : null} //FIXME unsafe
                        showLevelColumn={this.props.collectionConfig.usesLayeredModel()}
                    />
                )
            }
        } else { //if there are no stats available
            analysisBlock = (<h5>This collection is available in the registry, but is absent in the media suite index</h5>)
        }

        return (
            <div className={IDUtil.cssClassName('collection-analyser')}>

                <div className="row">
                    <div className="col-md-12">
                        {analysisBlock}
					</div>
				</div>

                {/* only toggle visibility to keep the component state */}
                <div style={{display: this.state.showFieldSelector ? 'block' : 'none'}}>
                    {fieldSelector}
                </div>

			</div>
		)
	}
}

CollectionAnalyser.propTypes = {
    collectionConfig: PropTypes.object.isRequired,
    onChange: PropTypes.func.isRequired,
    onCompletenessLoaded: PropTypes.func.isRequired
};
export default CollectionAnalyser;
