import React, { Component } from 'react';

import Modal, { ModalTitle, ModalContent } from './Modal';
import ActivityIndicator from './ActivityIndicator';

import { Iterable } from 'immutable';

require("./SelectModal.scss");


class SelectModal extends Component {

	constructor(props) {
		super(props);

		this.showModal = this.showModal.bind(this);
		this.fetchData = this.fetchData.bind(this);
		this.selectValue = this.selectValue.bind(this);
		this.clearValue = this.clearValue.bind(this);
		this.hideModal = this.hideModal.bind(this);

		this.state = {
			isPending: false,
			modal: false, 
			filter: "",
			list: []
		}
	}


	async showModal() {
		this.setState({ modal: true });
		await this.fetchData();
	}

	
	hideModal() {
		this.setState({ modal: false });
	}


	async fetchData() {
		let { fetchData } = this.props;
		if (typeof fetchData !== "function") {
			return [];
		}

		this.setState({ isPending: true });
		let list = [];
		try {
			list = await fetchData() || [];
		} catch (e) {
			console.error(e);
		}
		this.setState({ isPending: false, list });
	}


	selectValue(value) {
		let { onChange, disabled } = this.props;
		if (disabled) {
			return;
		}
		if (typeof onChange === "function") {
			onChange(value);
		}
		this.hideModal();
	}


	clearValue(value) {
		let { onChange, disabled } = this.props;
		if (disabled) {
			return;
		}
		if (typeof onChange === "function") {
			onChange(null);
		}
	}


	render() {
		let { renderList, readInputValue, disabled, label } = this.props;
		
		let list = null;
		if (typeof renderList === "function") {
			list = renderList(this.state.list, this.selectValue, this.hideModal);
		}

		let value = null;
		if (typeof readInputValue === "function") {
			value = this.props.value;
			if (Iterable.isIterable(value)) {
				value = value.toJS();
			}
			value = readInputValue(value) || "";
		}

		//TODO css - min height
		return (
			<div className={ `select-modal-field  ${this.props.className || "" }` }>
				<input type="text" readOnly="true" value={ value } />
				<button type="button" onClick={ this.showModal } disabled={ disabled }>select</button>
				<button type="button" onClick={ this.clearValue } disabled={ disabled }>clear</button>

				<Modal show={ this.state.modal } onClose={ () => this.setState({ modal: false }) } closeButton>
					<ModalTitle>{ label }</ModalTitle>
					<ModalContent>
						{ list }
						<ActivityIndicator show={ this.state.isPending } type="overlay" />
					</ModalContent>
				</Modal>
			</div>
		);
	}

}


export default SelectModal;
