/**
 * Repositories Dashboard component
 * This is a Smart React component that will be connected to the Redux store
 *
 */

import AJS from 'aui';
import { get } from 'lodash';
import { Component, PropTypes }from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';

import Spinner from 'bitbucket/internal/bbui/aui-react/spinner';

import loadRecentRepositories from './action-creators/load-recent-repositories';
import RepositoryList from './components/repository-list';
import RepositorySearch from './components/repository-search';

export class Repositories extends Component {

    componentWillMount() {
        this.props.loadRecentRepositories();
    }

    onMoreClick() {
        if (this.props.loadMore) {
            this.props.loadMore();
        } else {
            this.props.loadRecentRepositories(this.props.nextStart);
        }
    }

    render() {
        return (
            <div id="dashboard-repositories" className="dashboard-repositories">
                <h3>{AJS.I18n.getText('bitbucket.web.dashboard.repositories.title')}</h3>

                <RepositorySearch />

                <RepositoryList
                    repositories={this.props.repositories}
                    showMore={!this.props.isLastPage && !this.props.isLoading}
                    onMoreClick={() => this.onMoreClick()}
                />

                {this.props.isLoading ? <Spinner /> : null}
            </div>
        );
    }
}

Repositories.propTypes = {
    loadRecentRepositories: PropTypes.func.isRequired,
};

function mapDispatchToProps(dispatch) {
    return bindActionCreators({
        loadRecentRepositories,
    }, dispatch);
}

function mapStateToProps(state) {
    const props = {
        isLoading: state.ui.repositoriesLoading,
        isLastPage: true,
    };

    // TODO - extract to a selector function to allow for testing
    const pagingInfo = get(state.paging, state.ui.activeRepositoryList);
    if (pagingInfo) {
        props.repositories = pagingInfo.repositories.map(key => state.repositories[key]);
        if (pagingInfo.loadMoreCallback) {
            props.loadMore = pagingInfo.loadMoreCallback;
        } else {
            props.nextStart = pagingInfo.lastPageMeta.nextStart;
        }
        props.isLastPage = pagingInfo.lastPageMeta.isLastPage;
    }

    return props;
}

export default connect(mapStateToProps, mapDispatchToProps)(Repositories);