import React from 'react';
import {render} from 'react-dom';
import Main from './components/Main';
import Welcome from './components/Welcome';

const getInitialState = url => {
  const params = window.location.search.substr (1).split ('&');

  const initialState = {
    rooms: {},
    category: {},
  };

  for (const param of params) {
    const [key, value] = param.split ('=');
    if (key === 'rooms' && value !== '') {
      initialState.rooms = {};
      value.split (',').forEach (k => {
        initialState.rooms[parseInt (k)] = true;
      });
    }

    if (key === 'category' && value !== '') {
      initialState.category = {};
      value.split (',').forEach (k => {
        initialState.category[parseInt (k)] = true;
      });
    }

    if (key === 'sort') {
      initialState.sort = value;
    }

    if (key === 'bounds') {
      initialState.bounds = value;
    }

    if (key === 'listingId') {
      initialState.listingId = value;
    }

    if (key === 'adType') {
      initialState.adType = value;
    }

    if (key === 'zoom') {
      initialState.zoom = parseInt (value);
    }

    if (['minSize', 'maxSize', 'minPrice', 'maxPrice'].includes (key)) {
      initialState[key] = parseFloat (value);
    }
  }

  return initialState;
};

const root = document.getElementById ('root');
const initialState = getInitialState (window.location);

const renderMain = (additionalState = {}) => {
  const main = <Main initialState={{...initialState, ...additionalState}} />;
  render (main, root);
};

//renderMain ();

// disable temp

if (
  Object.keys (initialState).length === 2 &&
  window.localStorage.getItem ('lastLoad') == null
) {
  const onSearch = ({adType}) => {
    
    console.log("onSearch()");
    //window.location = `/?adType=${adType}`;
    renderMain({adType})
  };
  const welcome = <Welcome onSearch={onSearch} />;
  render (welcome, root);
} else {
  renderMain ();
}
