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

import Project from './model/Project';
import ProjectAPI from './api/ProjectAPI';

import ToolHeader from './components/shared/ToolHeader';
import ProjectQueriesTable from './components/workspace/projects/query/ProjectQueriesTable';
import QueryTimelinePlotter from "./components/stats/QueryTimelinePlotter";

import IDUtil from './util/IDUtil';
import FlexRouter from './util/FlexRouter';
import LocalStorageHandler from './util/LocalStorageHandler';

export default class QueryComparisonRecipe extends React.Component {

    constructor(props) {
        super(props);

        const activeProject = Project.construct(
            LocalStorageHandler.getJSONFromLocalStorage('stored-active-project')
        )
        const selectedQueries = this.initSelectedQueries(activeProject);
        this.state = {
            activeProject : activeProject,

            selectedQueries : selectedQueries,
            userProjects : []
        };
        PropTypes.checkPropTypes(QueryComparisonRecipe.propTypes, this.props, 'prop', this.constructor.name);
    }

    initSelectedQueries = activeProject => {
        //check if there are queries selected
        const storedQueryData = LocalStorageHandler.getStoredQueries();
        if(!activeProject || !storedQueryData || activeProject.id !== storedQueryData.projectId) return [];

        const namedQueries = activeProject.queries.filter(nq => {
            const ok = storedQueryData.queryIds.includes(nq.id)
            return ok
        }
        ).map(nq => { //Note: this is needed for the queryInfoBlocks to be rendered properly
            Object.assign(nq.query, {searchId: IDUtil.guid()});
            return nq;
        });
        return namedQueries
    };

    componentDidMount = () => {
        // Get projects list for current user
        ProjectAPI.list(this.props.user.id, null, projects => this.setState({
                userProjects: projects
            })
        );
    };

    onComponentOutput = (componentClass, data) => {
        if(componentClass === 'ToolHeader') {
            this.setState(
                {
                    activeProject: data,
                    selectedQueries : this.initSelectedQueries(data)
                },
                () => LocalStorageHandler.storeJSONInLocalStorage('stored-active-project', data)
            );
        }
    };

    compareQueries = tableSelection => {
        const namedQueries = tableSelection.map(nq => {
            Object.assign(nq.query, {searchId: IDUtil.guid()});
            return nq;
        });
        LocalStorageHandler.storeQueries(
            this.state.activeProject,
            tableSelection.map(nq => nq.id)
        );
        this.setState({selectedQueries : namedQueries});
    };

    clearQueriesInfoBlocks = () => this.setState({
        selectedQueries: []
    });

    /* --------------------------- RENDER HEADER --------------------- */

    render() {
        const projectQueriesTable = this.state.activeProject ? (
            <ProjectQueriesTable
                key={this.state.activeProject.id}
                handleCompareLink={this.compareQueries}
                handleDeleteQueries={this.clearQueriesInfoBlocks}
                project={this.state.activeProject}
                user={this.props.user}
                selection={this.state.selectedQueries}
                keepSelectionWhenDone={true}
            />
        ) : null;

        return (
            <div className={IDUtil.cssClassName('comparative-search-recipe')}>
                <ToolHeader
                    name="Compare"
                    projects={this.state.userProjects}
                    activeProject={this.state.activeProject}
                    onOutput={this.onComponentOutput}
                    user={this.props.user}
                    key={'header-tools__' + (
                        this.state.userProjects ? this.state.userProjects.length : 0
                    )}
                />
                <div className="workspace-components">
                    <button className="btn btn-primary" onClick={() => FlexRouter.gotoSingleSearch()}>Add query</button>
                    {projectQueriesTable}
                </div>
                <QueryTimelinePlotter
                    //for now always rerender the whole thing, since only componentDidMount is used to load data
                    key={IDUtil.guid()}
                    clientId={this.props.clientId}
                    user={this.props.user}
                    namedQueries={this.state.selectedQueries}
                />
            </div>
        );
    }
}

QueryComparisonRecipe.propTypes = {
    clientId : PropTypes.string.isRequired, // Required by __loadCollectionMetadata() in CollectionUtil
    params: PropTypes.object,
    recipe: PropTypes.shape({
        description: PropTypes.string,
        id: PropTypes.string,
        inRecipeList: PropTypes.bool,
        name: PropTypes.string.isRequired, // Use for when rendering header (isRequired by <ToolHeader/>)
        phase: PropTypes.string,
        recipeDescription: PropTypes.string,
        type: PropTypes.string,
        url: PropTypes.string,
        ingredients: PropTypes.shape({
            resourceViewerPath: PropTypes.string,
            collection: PropTypes.string,
            collectionSelector: PropTypes.bool,
            dateRangeSelector: PropTypes.string,
            aggregationView: PropTypes.string,
            useProjects: PropTypes.bool
        }).isRequired
    }).isRequired,
    user: PropTypes.shape({
        id: PropTypes.string.isRequired,
        name: PropTypes.string,
        attributes: PropTypes.shape({
            allowPersonalCollections: PropTypes.bool
        })
    }).isRequired
};
