import { PORTAL_PREFIX } from '../constants/appConstants';
import fetch from 'isomorphic-fetch';

/**
 * Get the authentication object
 */
export const getAuthObject = () => {
  const initialAuth = {
    username: null,
    askForPin: false,
    isLoggedIn: false,
    data: null
  };

  try {
    let auth = getCookie('ster_auth');
    return auth ? JSON.parse(auth) : initialAuth;
  }
  catch (exception) {
    return initialAuth;
  }
};

/**
 * Get bearer token
 */
export const getToken = () => {
  let auth = getAuthObject();
  if(auth.data && auth.data.access_token) {
    return auth.data.access_token;
  }

  return null;
};

/**
 * Set extra Ster headers
 */
export const setExtraHeaders = (config) => {
  let auth = getAuthObject();
  if(auth.data && auth.isInternalUser) {
    let orgcode = getCookie('ster_orgcode');
    if(orgcode) {
      config.headers['X-Portal-OrganisationCode'] = orgcode;
    }
  }

  return config;
};

/**
 */
export const getOrganisationCode = () => {
  let orgcode = getCookie('ster_orgcode');
  return orgcode;
};

/**
 * Has role in roles array
 */
export const hasRole = (roleName, rolesArray) => {
  if(rolesArray && rolesArray.length > 0) {
    let role = rolesArray.find(r => (r === roleName));
    if(role) {
      return true;
    }
  }

  return false;
};

/**
 * Check the response object-status
 */
export const checkResponse = (response, redirect401 = true) => {
  if (response.status === 401 && redirect401) {
    window.location.replace(`${PORTAL_PREFIX}login`);
  }

  if (response.status >= 400) {
    throw new Error('Bad response from server');
  }
};

/**
 * Post the body as form-data
 */
export const post = (url, body) => {
  let config = {
    method: 'POST',
    headers: {
      'Content-type': 'application/json',
      'Accept': 'application/json',
    },
    body: body.join('&')
  };

  return fetch(url, config);
};

/**
 * Post the body as form-data
 */
export const postForm = (url, body) => {
  let config = {
    method: 'POST',
    headers: {
      'Content-type': 'application/x-www-form-urlencoded',
    },
    body: body.join('&')
  };

  return fetch(url, config);
};

/**
 * Post body-object as JSON-string
 * With a 'Bearer' token included
 */
export const postJsonWithToken = (url, body) => {
  let config = {
    method: 'POST',
    headers: {
      'Content-type': 'application/json',
      'Accept': 'application/json',
      'Authorization': 'Bearer ' + getToken()
    },
    body: JSON.stringify(body)
  };

  config = setExtraHeaders(config);

  return fetch(url, config);
};

/**
 * Get URL
 * Without a 'Bearer' token included
 */
export const get = (url, params = []) => {
  let config = {
    method: 'GET',
    headers: {
      'Content-type': 'application/json',
      'Accept': 'application/json',
    }
  };

  return fetch(`${url}?${params.join('&')}`, config);
};

/**
 * Get URL
 * With a 'Bearer' token included
 */
export const getWithToken = (url, params = []) => {
  let config = {
    method: 'GET',
    headers: {
      'Content-type': 'application/json',
      'Accept': 'application/json',
      'Authorization': 'Bearer ' + getToken()
    }
  };

  config = setExtraHeaders(config);

  return fetch(`${url}?${params.join('&')}`, config);
};

/**
 *
 */
export function* range(from, to, step = 1) {
  for (let i = from; i < to; i += step) {
    yield i;
  }
}

/**
 * Creates new cookie or removes cookie with negative expiration
 * @param - key   - The key or identifier for the store
 * @param - value - Contents of the store
 * @param - exp   - Expiration
 */
export const setCookie = (key, value, exp) => {
  let date = new Date();
  date.setTime(date.getTime() + (exp * 24 * 60 * 60 * 1000));

  let domain = null;
  if(location.hostname.indexOf('ster.nl') > -1) {
    domain = 'ster.nl';
  }

  if(domain) {
    document.cookie = `${key}=${value};expires=${date.toGMTString()};domain=${domain};path=/`;
  }
  else {
    document.cookie = `${key}=${value};expires=${date.toGMTString()};path=/`;
  }
};

/**
 * Returns contents of cookie
 * @param - key - The key or identifier for the store
 */
export const getCookie = (key) => {
  let nameEQ = key + '=';
  let ca = document.cookie.split(';');
  for (let i = 0, max = ca.length; i < max; i++) {
    let c = ca[i];
    while (c.charAt(0) === ' ') {
      c = c.substring(1, c.length);
    }

    if (c.indexOf(nameEQ) === 0) {
      return c.substring(nameEQ.length, c.length);
    }
  }

  return null;
};
