import React from 'react';
import Modularity from 'modularity-front';
import { Row, Col, Button } from 'react-materialize';

import SearchBar from '../../Modules/searchbar.js';
import API from '../../Services/API.js';

import './SearchBarPackage.css';

let Module = Modularity.Module;
class SearchBarPackage extends Modularity.Module {
	constructor(props) {
		super(props);
		this.state = {
            suggestions: {},
            printerSuggestions: {},
            text: ''
		}

        this.api = new API();
        // this.Token.onUpdate((v) => { this.back_service.Token.update(v);this.forceUpdate(); });
	}

    getSuggestions(value) {
        if(!value || value.length !== 3) return;
        this.api.get('/products/search/' + value).then((suggestions) => {
            return suggestions;
        }).then((suggestions) => {
            return suggestions.reduce((res, s) => {
                res[s.name] = { image: s.image, key: s.name, id: s.id };
                return res;
            }, {});
        }).then((suggestions) => 
            this.setState({
                suggestions,
                text:value
            })
        );
        this.api.get('/printers/search/' + value)
        .then((suggestions) => {
            return suggestions.reduce((res, s) => {
                res[s.name] = { image: s.image, key: s.name, id: s.id, printer: true };
                return res;
            }, {});
        })
        .then((printerSuggestions) => {
            this.setState({
                printerSuggestions,
                text:value
            });
        });
    }

    search(data) {
        console.log("SEARCH" , data);
        if(data && data.printer)
            this.CoreSystem.go("/printer/" + data.id);
        else if(data) 
            this.CoreSystem.go("/search/" + data.key);
    }

	render() {
        console.log("Suggestions:", this.state.suggestions);
        return  <div>
            <SearchBar Data={{...this.state.printerSuggestions, ...this.state.suggestions}} SearchBar={{placeholder: "Search"}} Text={(v) => this.getSuggestions(v)} ObjectData={(data) => this.search(data)} className={"SearchBarPackage " + this.ClassName.value} />
            {super.render()}
        </div>;
	}
}


SearchBarPackage.Inputs = {
    SearchRoute: {
        type: Module.Types.Text,
        defaultValue: '/search'
    },
    ClassName: {
        type: Module.Types.Text,
        defaultValue: ''
    }
}

SearchBarPackage.Category = "NikatlasPackages";
SearchBarPackage.EditPosition = "top-center";
export default SearchBarPackage;