import React, {Component} from 'react';

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

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

enum Conlang {
    Saimiar = 'saimiar',
    Elesu = 'elesu',
    Tukvaysi = 'tukvaysi',
    Juteyuji = 'juteyuji',
}

enum SearchDirection {
    ToConlang,
    ToEnglish
}

const renderConlang = (conlang: Conlang): string => {
    if (conlang === Conlang.Saimiar) {
        return 'Saimiar';
    }

    if (conlang === Conlang.Elesu) {
        return 'Elésu';
    }

    if (conlang === Conlang.Juteyuji) {
        return 'Juteyuji';
    }

    if (conlang === Conlang.Tukvaysi) {
        return 'Tukvaysi';
    }
};

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

const Entry = (props) => {
    const {conlang} = props;
    if (conlang === Conlang.Saimiar) {
        return <SaiEntry entry={ props.entry } />;
    }

    if (conlang === Conlang.Juteyuji) {
        return <JutEntry entry={ props.entry } />;
    }

    return <div>Conlang { conlang } not yet supported</div>;
};

const SaiEntry = (props) => {
    const {entry} = props;
    const synCategory = entry.syn_category;
    const isNominal = synCategory === 'nominal';
    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>
    );
};

const JutEntry = (props) => {
    const {entry} = props;
    console.log(props);

    return (
        <div className="searchResult" key={ entry.id }>
            <b>{ entry.jut }</b> - { entry.eng }
            <br/>
            <span className="synclass">
                { entry.syn_category === 'noun' ? entry.gender : null }
            </span>
        </div>);
};

function formatMorphology(entry) {
    const decl = declineSaimiar(entry);
    if (!decl) {
        return '';
    }

    return (<span style={ {fontSize: 'medium', color: '#6a3131'} } >
        Abs: <i>{decl.abs}</i>, Erg: <i>{decl.erg}</i>,
        Adp: <i>{decl.adp}</i>,
        All: <i>{decl.all}</i>,
        Loc: <i>{decl.loc}</i>,
        Ell: <i>{decl.ell}</i>,
        Inst: <i>{decl.inst}</i>,
        Rel: <i>{decl.rel}</i>
    </span>);
}

const Results = (props) => {
    const content = () => {
        const {conlang} = props;
        const num = props.searchResults.length;

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

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

interface App {
    [x: string]: any;
}

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.searchJuteyuji = this.searchJuteyuji.bind(this);
        this.searchConlang = this.searchConlang.bind(this);

        this.state = {
            searchResults: null,
            conlang: Conlang.Saimiar,
            direction: null,
            searchTerm: null,
        };
    }

    searchConlang(_evt) {
        const searchTerm = this.input.current.value;
        const {conlang} = this.state;
        if (conlang === Conlang.Saimiar) {
            this.searchSaimiar(searchTerm);
        } else if (conlang === Conlang.Juteyuji) {
            this.searchJuteyuji(searchTerm);
        } else {
            console.error(`Conlang ${conlang} not supported`);
        }
    }

    searchSaimiar(searchTerm: string) {
        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: SearchDirection.ToEnglish});
            });
        }
    }

    searchJuteyuji(searchTerm: string) {
        const request = `juteyuji?jut=like.*${searchTerm}*`;
        if (searchTerm === '') {
            this.setState({searchResults: null, searchTerm: null, direction: null});
        } else {
            makeRequest(request, (json) => {
                this.setState({searchResults: json, searchTerm, direction: SearchDirection.ToEnglish});
            });
        }
    }

    searchEng(_evt) {
        const searchTerm = this.input.current.value;
        const {conlang} = this.state;
        const request = `${conlang}?eng=like.*${searchTerm}*`;
        if (searchTerm === '') {
            this.setState({searchResults: null, searchTerm: null});
        } else {
            makeRequest(request, (json) => {
                this.setState({searchResults: json, searchTerm, direction: SearchDirection.ToConlang});
            });
        }
    }

    handleLangChange(evt) {
        const conlang: Conlang = evt.target.value as Conlang;
        console.log('Conlang in handlelangchange', conlang);
        this.setState({conlang, searchResults: null});
    }

    render() {
        const conlangs = [Conlang.Saimiar, Conlang.Elesu, Conlang.Tukvaysi, Conlang.Juteyuji];
        const langSelectDropdown = (
            <select ref={ this.langSelection } onChange={ this.handleLangChange } defaultValue={Conlang.Saimiar}>
                {conlangs.map((conlang) => <option value={conlang} key={conlang}>{renderConlang(conlang)}</option>)}
            </select>
        );

        return (
            <main>
                <div className="container">
                    <div className="search">
                        <h1>Kucinako</h1>
                        <div className="textInput">
                            <input className="textInput" type="text" ref={ this.input } />
                        </div>
                        <br/>
                        { langSelectDropdown }
                        <button onClick={ this.searchConlang } className="searchButton">{renderConlang(this.state.conlang)}</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;
