import * as React from 'react';
import * as _ from 'lodash';
import * as DefaultStyles from './style';

/**
 * Refactor this component to be more generic
 */

export namespace ListItem {
    export interface Props {
        item: any;
        index: number;
        onClick: (item: any) => void;
        onEditClick: (item: any) => void;
        styles?: any;
    }

    export interface State {
        mouseOverItem: number,
    }

    export interface Styles {
        ItemContainer?: any,
        ItemTitleContainer?: any,
        TextItem?: any,
    }
}
export default class ListItem extends React.Component<ListItem.Props, ListItem.State> {

    constructor(props: ListItem.Props) {
        super(props);
        this.state = {
            mouseOverItem: -1
        };
        this.handleMouseOver = this.handleMouseOver.bind(this);
        this.handleMouseLeave = this.handleMouseLeave.bind(this);
        this.onItemClick = this.onItemClick.bind(this);
        this.onItemEditClick = this.onItemEditClick.bind(this);

    }

    handleMouseOver(e) {
        let newMouseOverIndex = parseInt(e.target.id.replace(/item/g, ''));
        if (!isNaN(newMouseOverIndex)) {
            this.setState({
                mouseOverItem: newMouseOverIndex
            });
        }

    }

    handleMouseLeave(e) {
        this.setState({
            mouseOverItem: -1
        });
    }

    onItemClick() {
        this.props.onClick(this.props.item);
    }

    onItemEditClick() {
        this.props.onEditClick(this.props.item);
    }

    render() {
        const Styles: ListItem.Styles = _.assignIn({ ...DefaultStyles }, _.pickBy(this.props.styles));
        return (
            <Styles.ItemContainer
                id={'item_' + this.props.index}
                key={'item_' + this.props.index}
                onMouseOver={this.handleMouseOver}
                onMouseLeave={this.handleMouseLeave}
            >

                <Styles.TextItem>{this.props.item.name}</Styles.TextItem>

            </Styles.ItemContainer>
        )
    }
}