import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';

import Project from '../../model/Project';
import Query from '../../model/Query';

import ProjectAPI from '../../api/ProjectAPI';
import IDUtil from '../../util/IDUtil';
import MessageHelper from "../helpers/MessageHelper";
import FlexBox from '../FlexBox';
import ProjectQueriesTable from '../workspace/projects/query/ProjectQueriesTable';
import ProjectList from "../search/ProjectList";

class QueryEditor extends React.PureComponent {

	constructor(props) {
		super(props);
		this.state = {
            errorMessage: false,
            selectedProject: this.props.project
		};
        this.queryNameRef = React.createRef();
		this.CLASS_PREFIX = 'qed';
	}

    //communicate the result back to the owning component
    onOutput(data) {
        if(data) {
            this.setState({
                project: data.project
            })
        }
        if(this.props.onOutput) {
            this.props.onOutput(this.constructor.name, data);
        }
    }

	save = e => {
		e.preventDefault();

		// require query name value
        if(!this.queryNameRef.current.value){
            this.setState({
                errorMessage: true
            });
            return;
        }

		if(this.props.query) {
            const project = this.state.selectedProject;
			const query = Query.construct(this.props.query);
			query.id = IDUtil.guid(); //always assign a new ID, since this component only supports saving new queries
			project.queries.push({
				name : this.queryNameRef.current.value,
				query : query
			});
			this.saveProject(this.props.user.id, project, this.queryNameRef.current.value)
		} else { //this should never happen though
			this.onOutput(null);
		}
	};

    saveProject = (userId, project, queryName) => {
        // store project
        ProjectAPI.save(userId, project, savedProject => {
            if (savedProject) {
                this.onOutput({project : savedProject, queryName: queryName});
            } else {
                alert('An error occured while saving this project');
                this.onOutput(null);
            }
        });
    };

    onSelectProject = project => {
        if(project && project.name) {
            this.setState({
                selectedProject: project
            })
        }
    };

    //----------------------------- RENDER FUNCTIONS -------------------------------

    renderValidationFailed = () => {
        return (
            <div className={IDUtil.cssClassName('validation-error', this.CLASS_PREFIX)}>
               Please name the query before saving it.
            </div>
        );
    };

    renderProjectList = (activeProject, userProjects, user, onSelectProject) => (
        <ProjectList
            activeProject={activeProject}
            onSelect={onSelectProject}
            projects={userProjects}
            user={user}
        />
    );

    renderQueryForm = errorMessage => {
        return (
            <form onSubmit={this.save}>
                <input type="text" ref={this.queryNameRef} placeholder="Name your query"/>
                <button type="submit" className="btn btn-default">Save</button>
                {errorMessage ? this.renderValidationFailed() : null}
            </form>
        );
    };

    renderQueryDetails = (query, collectionConfig) => (
        <div className={IDUtil.cssClassName('query-params', this.CLASS_PREFIX)}>
            {MessageHelper.renderQuery(query, collectionConfig)}
        </div>
    );

    renderQueryTable = (project, user) => {
        if(project === null || project.queries.length === 0) {
            return null;
        }

        return (
            <FlexBox isVisible={false} title={'Other queries saved in: ' + project.name}>
                <div className={[
                    IDUtil.cssClassName('no-bootstrap-custom-styling'),
                    IDUtil.cssClassName('table', this.CLASS_PREFIX)].join(' ')
                }>
                    <ProjectQueriesTable project={project} user={user}/>
                </div>
            </FlexBox>
        );
    };

	render() {
        const projectList = this.renderProjectList(
            this.state.selectedProject,
            this.props.userProjects,
            this.props.user,
            this.onSelectProject
        );
        const queryForm = this.state.selectedProject ? this.renderQueryForm(this.state.errorMessage): null;

        const queryDetails = this.state.selectedProject ?
            this.renderQueryDetails(
                this.props.query,
                this.props.collectionConfig
            ) : null;

		const queryTable = this.state.selectedProject ?
            this.renderQueryTable(this.state.selectedProject, this.props.user) :
            null
        ;

        return (
			<div className={IDUtil.cssClassName('query-editor')}>
                <div
                    title={this.state.selectedProject ? "Current user project. Click to change." : ""}
                    style={{float: this.state.selectedProject ? 'right' : 'none'}}
                >
                    {projectList}
                </div>
				{queryForm}
                {queryDetails}
				{queryTable}
			</div>
		)
	}

}

QueryEditor.propTypes = {
    // current user object used for defining access roles per project
    user: PropTypes.shape({
        id: PropTypes.string.isRequired,
        name: PropTypes.string,
        attributes: PropTypes.shape({
            allowPersonalCollections: PropTypes.bool
        })
    }),
    userProjects : PropTypes.array,
    project: Project.getPropTypes(false),
    collectionConfig : PropTypes.object.isRequired,
    query: PropTypes.object.isRequired,
    onOutput: PropTypes.func.isRequired
};

export default QueryEditor;
