export const SET_CONNECTING = `mercury/SET_CONNECTING`;
export const SET_CONNECTED = `mercury/SET_CONNECTED`;

export function updateStatusConnecting(value) {
  return {
    type: SET_CONNECTING,
    payload: value
  };
}

export function updateStatusConnected(value) {
  return {
    type: SET_CONNECTED,
    payload: value
  };
}


export function connectToMercury(sparkInstance) {
  return (dispatch) => {
    if (sparkInstance) {
      const {
        canAuthorize,
        device,
        mercury
      } = sparkInstance;

      if (canAuthorize && device.registered
        && !mercury.connected && !mercury.connecting) {
        dispatch(updateStatusConnecting(true));
        sparkInstance.mercury.connect().then(() => {
          sparkInstance.listenToAndRun(mercury, `change:connected`, () => {
            dispatch(updateStatusConnected(mercury.connected));
          });
        });
      }
    }
  };
}


export const SET_CONNECTING = `mercury/SET_CONNECTING`;
export const SET_CONNECTED = `mercury/SET_CONNECTED`;

export function updateStatusConnecting(value) {
  return {
    type: SET_CONNECTING,
    payload: value
  };
}

export function updateStatusConnected(value) {
  return {
    type: SET_CONNECTED,
    payload: value
  };
}


export function connectToMercury(sparkInstance) {
  return (dispatch) => {
    if (sparkInstance) {
      const {
        canAuthorize,
        device,
        mercury
      } = sparkInstance;

      if (canAuthorize && device.registered
        && !mercury.connected && !mercury.connecting) {
        dispatch(updateStatusConnecting(true));
        sparkInstance.mercury.connect().then(() => {
          sparkInstance.listenToAndRun(mercury, `change:connected`, () => {
            dispatch(updateStatusConnected(mercury.connected));
          });
        });
      }
      // Handle if mercury is already connected from previous instance
      else if (mercury.connected) {
        dispatch(updateStatusConnected(mercury.connected));
      }
    }
  };
}


Set mercury to connected if already connected from instance
feat(redux-module-mercury): Set mercury to connected if already connected from instance
