import fetch from 'isomorphic-fetch'
import {BASE_URL} from '../../../common/config'

export const saveContactRequest = (listingId, params) => {

  let url = `http://${BASE_URL}/api/contact/${listingId}`

  return fetch(url, {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(params)
  });
}

export const loadListing = id => {
  let url = `http://${BASE_URL}/api/search/listings/${id}`

  return fetch(
    url,
    {
      //credentials: 'include'
    }
  )
}

export const loadProperties = (
  {
    bounds,
    minPrice = '',
    maxPrice = '',
    minSize = '',
    maxSize = '',
    rooms = {},
    category = {},
    adType=1,
    page = 1,
    pins = false,
    sort = ''
  }
) => {
  const allRooms = Object.keys(rooms).filter(v => rooms[v]).join(',')

  const allCategories = Object.keys(category)
    .filter(v => category[v])
    .join(',')

  // TODO: handle errors
  //return fetch(process.env.API_URL + '/api/search', {
  let url = `http://${BASE_URL}/api/search/listings?bounds=${bounds}&minPrice=${minPrice}&maxPrice=${maxPrice}&rooms=${allRooms}&minSize=${minSize}&maxSize=${maxSize}&adType=${adType}&category=${allCategories}&page=${page}&pins=${pins}&sort=${sort}`

  return fetch(
    url,
    {
      //credentials: 'include'
    }
  )
}

export const markSeen = id => {
  const seen = JSON.parse(window.localStorage.getItem('seen') || '[]')
  seen.push(id)
  window.localStorage.setItem('seen', JSON.stringify(seen))
}

export const loadSeen = id => {
  const seen = JSON.parse(window.localStorage.getItem('seen') || '[]')
  return seen
  //return seen.findIndex(s => s === id) !== -1;
}

