import React, { Component } from "react";

import './App.scss';
import { declineSaimiar } from './saimiar_morphology.js';

const backendUrl = "https://kucinakobackend.ichigo.everydayimshuflin.com";

function makeRequest(queryString, jsonHandler) {
  const effectiveUrl = `${backendUrl}/${queryString}`
  fetch(`${effectiveUrl}`)
    .then((resp) => {
      return resp.json()
    })
    .then((json) => {
      jsonHandler(json);
    });
}

function renderConlangName(name) {
  if (name == "saimiar") {
    return "Saimiar";
  }
  if (name == "elesu") {
    return "Elésu";
  }

  if (name === "juteyuji") {
    return "Juteyuji";
  }
  if (name === "tukvaysi") {
    return "Tukvaysi";
  }
}

function Entry(props) {
  const conlang = props.conlang;
  if (conlang === "saimiar") {
    return <SaiEntry entry={ props.entry } />;
  }
  return <div>Unknown entry type for { conlang }</div>;
}

function SaiEntry(props) {
  const entry = props.entry;
  const synCategory = entry.syn_category;
  const isNominal = synCategory == 'nominal';
  console.log(isNominal);
  return (
    <div className="searchResult" key={ entry.id }>
      <b>{ entry.sai }</b> - { entry.eng }
      <br />
      <span className="synclass">
        <i>{ entry.syn_category }</i>
        { entry.morph_type ? `\t\t${entry.morph_type}` : null }
        <br/>
        { isNominal ? formatMorphology(entry) : null }
      </span>
    </div>
  );
}

function formatMorphology(entry) {
  const decl = declineSaimiar(entry);
  if (!decl) {
    return '';
  }
  return `Abs: ${decl.abs}, Erg: ${decl.erg}, Adp: ${decl.adp}`;
}

class Results extends Component {
  constructor(props) {
    super(props);
    this.content = this.content.bind(this);
  }

  content() {
    const conlang = this.props.conlang;
    const num = this.props.searchResults.length;
    const renderedName = renderConlangName(conlang);
    const searchType = (this.props.direction === "toConlang") ? `English -> ${renderedName}` : `${renderedName} -> English`;
    const header = (
      <div className="searchResultHeader" key="header">
        Searched for <b>{ this.props.searchTerm }</b>, { searchType }, found { num } result(s)
      </div>);
    const entries = this.props.searchResults.map(
      (entry, idx) => <Entry entry={ entry } key= { entry.id } conlang={ conlang } />
    );
    return [header].concat(entries);
  }

  render() {
    const results = this.props.searchResults;
    return(
      <div className='results'>
        { results ? this.content() : "No search" } 
      </div>
    );
  }
}

class App extends Component {
  constructor(props) {
    super(props);
    this.input = React.createRef();
    this.handleLangChange = this.handleLangChange.bind(this);

    this.searchEng = this.searchEng.bind(this);
    this.searchSaimiar = this.searchSaimiar.bind(this);

    this.state = {
      searchResults: null,
      conlang: "saimiar",
      direction: null,
      searchTerm: null
    };
  }

  searchSaimiar(evt) {
    const searchTerm = this.input.current.value;
    const request = `saimiar?sai=like.*${searchTerm}*`
    if (searchTerm === "") {
      this.setState({ searchResults: null, searchTerm: null, direction: null });
    } else {
      makeRequest(request, (json) => {
        this.setState({ searchResults: json, searchTerm, direction: "toEnglish" });
      });
    }
  }

  searchEng(evt) {
    const searchTerm = this.input.current.value;
    const request = `saimiar?eng=like.*${searchTerm}*`
    if (searchTerm === "") {
      this.setState({ searchResults: null, searchTerm: null, });
    } else {
      makeRequest(request, (json) => {
        this.setState({ searchResults: json, searchTerm, direction: "toConlang" });
      });
    }
  }

  handleLangChange(evt) {
    const conlang = evt.target.value;
    this.setState({ conlang });
  }

  render() {

    return(
      <main>
        <div className='container'>
          <div className='search'>
            <h1>Kucinako</h1>
            <div className='textInput'>
                <input className='textInput' type="text" ref={ this.input } />
            </div>
            <br/>
            <select ref={ this.langSelection } onChange={ this.handleLangChange } defaultValue="saimiar">
              <option value="saimiar">Saimiar</option>
              <option value="elesu">Elesu</option>
              <option value="tukvaysi">Tukvaysi</option>
              <option value="juteyuji">Juteyuji</option>
            </select>
            <button onClick={ this.searchSaimiar } className="searchButton">Saimiar</button>
            <button onClick={ this.searchEng } className="searchButton">English</button>
          </div>
          <Results
            searchResults={ this.state.searchResults }
            searchTerm= { this.state.searchTerm }
            conlang={ this.state.conlang }
            direction={ this.state.direction }
          />
        </div>
      </main>
    );
  }
}



export default App;
