import React from "react";
import { render } from "react-dom";
import SearchResults from "./components/SearchResults";
import { SEARCH_KEY_NAME, REACT_ROOT_DIV_ID, BEER_API_URL, BEER_API_SEARCH_PREFIX } from "./constants";
import getCurrentSearchString from "./lib/getCurrentSearchString";

function search(){
    getCurrentSearchString((searchQuery) =>{
        createRootDiv(()=>{
            const httpRequest = new XMLHttpRequest();
            httpRequest.onreadystatechange = (data) => {
                // TODO: handle errors :)
                if(httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
                    const json = JSON.parse(httpRequest.responseText);
                    render(<SearchResults q={searchQuery} data={json}/>, document.getElementById(REACT_ROOT_DIV_ID));
                };
            };
            httpRequest.open("GET", `${BEER_API_URL}${BEER_API_SEARCH_PREFIX}${searchQuery}`);
            httpRequest.send();
        });
    });
}

const createRootDiv = (cb) => {
    const elementExists = document.getElementById(REACT_ROOT_DIV_ID);
    if(!elementExists){
        let g = document.createElement("div");
        g.id = REACT_ROOT_DIV_ID;
        document.body.insertBefore(g, document.body.firstChild);
        return cb();
    } else {
        return cb();
    }
};

search();

export default search;

@@ -120,16 +120,31 @@
 import %7B
+ BEER_KEY_NAME,
  SEARCH_
@@ -298,16 +298,96 @@
 tring%22;%0A
+import setData from %22./lib/setData%22;%0A%0A/*%0A* Search beer data from Oluttamo API%0A*/
 %0Afunctio
@@ -455,26 +455,23 @@
     
-createRootDiv(()=%3E
+if(searchQuery)
 %7B%0A  
@@ -815,33 +815,39 @@
     
-render(%3CSearchResults q=%7B
+setData(BEER_KEY_NAME, %7Bquery: 
 sear
@@ -857,67 +857,105 @@
 uery
-%7D
+,
  data
-=%7B
+: 
 json
-%7D/%3E, document.getElementById(REACT_ROOT_DIV_ID)
+, url: window.location.href%7D);%0A                    addSearchResults(searchQuery, json
 );%0A 
@@ -1123,18 +1123,16 @@
        %7D
-);
 %0A    %7D);
@@ -1134,16 +1134,342 @@
   %7D);%0A%7D%0A
+%0A// render search results react element%0Afunction addSearchResults(searchQuery, data, showOnlyFooter=false)%7B%0A    createRootDiv(()=%3E%7B%0A        render(%3CSearchResults q=%7BsearchQuery%7D data=%7Bdata%7D showOnlyFooter=%7BshowOnlyFooter%7D/%3E, document.getElementById(REACT_ROOT_DIV_ID));%0A    %7D);%0A%7D%0A%0A// Create react root div it doesn't exist yet
 %0Aconst c

Move render to own function, add also beer data to storage