import React from 'react';
import SearchHeader from './SearchHeader';
import SearchResults from './SearchResults';

var HttpServices = require("./services/HttpServices");

class Search extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      searchText : this.props.location.state.searchText,
      userSelected: this.props.location.state.userSelected,
      lastQueryResults: this.props.location.state.lastQueryResults
    };

    this.onUpdateSearch = this.onUpdateSearch.bind(this);
    this.onSearch = this.onSearch.bind(this);
  }

  componentDidMount() {
    // if (!this.state.lastQueryResults.data) {
      // this.onSearch();
    // }
  }


  onUpdateSearch(updateValue) {

    this.setState({
        searchText : updateValue.searchText,
        userSelected : updateValue.userSelected,
        lastQueryResults : updateValue.lastQueryResults
      });
  }

  onSearch() {
    HttpServices.getWithoutAuth(`http://localhost:3000/api/doctorsearch/name?name=${this.state.searchText}`, (err, res) => {
      this.setState({
        lastQueryResults: res
      });
    });
  }

  render() {
    if (!this.state.lastQueryResults || this.state.lastQueryResults.searchedname != this.state.searchText) {
      this.onSearch();
    }
    return (
      <div className="Search-container">
        <SearchHeader searchText={this.state.searchText} onUpdateSearch={(updateValue) => this.onUpdateSearch(updateValue)}/>
        <SearchResults searchText={this.state.searchText} lastQueryResults={this.state.lastQueryResults} userSelected = {this.state.userSelected}/>
      </div>
    );
  }
}


export default Search
