import {API} from 'config';
import {isWeb, getCookie, setCookie} from 'utility';

const DARK_MODE = Symbol('DARK_MODE');

const DarkMode = ()=>{
  return async (dispatch, getState)=>{
    const dark = getState().Settings.dark;
    if(dark){
      document.body.classList.remove('dark');
      setCookie('dark_mode', 'off');
    } else {
      document.body.classList.add('dark');
      setCookie('dark_mode', 'on');
    }
    dispatch({
      type: DARK_MODE,
      dark: !dark,
    });
  };
};

const defaultState = {
  dark: false,
};

const initState = ()=>{
  const k = {};
  if(isWeb() && getCookie('dark_mode') === 'on'){
    k.dark = true;
    document.body.classList.add('dark');
  }
  return Object.assign({}, defaultState, k);
};

const Settings = (state=initState(), action)=>{
  switch(action.type){
    case DARK_MODE:
      return Object.assign({}, state, {
        dark: action.dark,
      });
    default:
      return state;
  }
};

export {
  Settings, DarkMode,
}

import {API} from 'config';
import {isWeb, getCookie, setCookie} from 'utility';

const DARK_MODE = Symbol('DARK_MODE');

let root = false;
if(isWeb()){
  root = document.getElementsByTagName('html')[0];
}

const DarkMode = ()=>{
  return async (dispatch, getState)=>{
    const dark = getState().Settings.dark;
    if(dark){
      root.classList.remove('dark');
      document.body.classList.remove('dark');
      setCookie('dark_mode', 'off');
    } else {
      root.classList.add('dark');
      document.body.classList.add('dark');
      setCookie('dark_mode', 'on');
    }
    dispatch({
      type: DARK_MODE,
      dark: !dark,
    });
  };
};

const defaultState = {
  dark: false,
};

const initState = ()=>{
  const k = {};
  if(isWeb() && getCookie('dark_mode') === 'on'){
    k.dark = true;
    root.classList.add('dark');
    document.body.classList.add('dark');
  }
  return Object.assign({}, defaultState, k);
};

const Settings = (state=initState(), action)=>{
  switch(action.type){
    case DARK_MODE:
      return Object.assign({}, state, {
        dark: action.dark,
      });
    default:
      return state;
  }
};

export {
  Settings, DarkMode,
}

add root element dark