import store from '../store';
import { isPopout } from './popouts';

export function getWidgetMapById(id, state = store.getState()) {
  let widgetIndex = null;
  let workspaceIndex = null;
  let widgetObj = null;
  if (id !== undefined) {
    state.workspaces.get('workspaceList').forEach((workspace, i) => {
      workspace.get('widgets').forEach((widget, n) => {
        if (widget.get('id') === id) {
          workspaceIndex = i;
          widgetIndex = n;
          widgetObj = widget;
        }
      });
    });
  }
  return [workspaceIndex, widgetIndex, widgetObj];
}

export function getWidgetById(id, state = store.getState()) {
  if (isPopout()) {
    return state.popouts.first();
  }
  return getWidgetMapById(id, state)[2];
}

export function mapAllWidgets(func, state = store.getState().workspaces) {
  return state.update('workspaceList', wsList => {
    return wsList.map(ws => {
      return ws.update('widgets', widgetList => {
        return widgetList.map(func);
      });
    });
  });
}
