import Failure from "core/failure";
import { Service } from "services/domain/serviceEntity";
import { notifyAction } from "ui/data/uiActions";
import { SubscriptionRequest } from "./dto/subscriptionRequest";
import * as actionTypes from "./subscriptionsActionTypes";
import { forkTo, loadSubscriptions, subscribe } from "./subscriptionsService";

const getSubscriptionsAction = () => (dispatch: any) => {
  dispatch({ type: actionTypes.SUBSCRIPTIONS_LOAD });

  return loadSubscriptions()
    .then((subscriptions) => {
      dispatch({
        type: actionTypes.SUBSCRIPTIONS_LOAD_SUCCESS,
        payload: subscriptions,
      });
    })
    .catch((failure: Failure) => {
      if (failure.meta?.isNetworkFailure) {
        notifyAction({
          title: "Network failure occured",
          body: failure.message,
          delay: 500,
        });
      }
      dispatch({
        type: actionTypes.SUBSCRIPTIONS_LOAD_FAILURE,
        payload: failure,
      });
    });
};

const subscribeAction = (payload: SubscriptionRequest) => async (dispatch: any): Promise<void> => {
  dispatch({ type: actionTypes.SUBSCRIBE_SERVICE, payload: payload.service_id });
  try {
    await subscribe(payload);
    dispatch({ type: actionTypes.SUBSCRIBE_SERVICE_SUCCESS, payload: payload.service_id });
  } catch (failure) {
    dispatch({
      type: actionTypes.SUBSCRIBE_SERVICE_FAILED,
      payload: payload.service_id,
    });
    return Promise.reject(failure);
  }
};

const getSessionAction = (id: Service["id"]) => (dispatch: any) => {
  dispatch({ type: actionTypes.SESSION_GET, payload: id });
  return forkTo(id);
};

export { getSubscriptionsAction, subscribeAction, getSessionAction };
