import { VIDEO_ALL_TAB, VIDEO_MY_TAB, VIDEO_SHARED_TAB } from '@/modules/@common/acl/constants';
import { VIDEO_TABS_ENUM } from '@/modules/editorial/editorialSearchFilter/constants';

import { hasPermission } from '@/modules/@common/user/helpers';

import { filterConfig } from '@/modules/editorial/editorialSearchFilter/filterConfig';

export const ifAllTabAvailable = (userPermissions) => hasPermission(VIDEO_ALL_TAB, userPermissions);

export const getTabsByPermissions = (userPermissions) => ({
  [VIDEO_TABS_ENUM.all]: hasPermission(VIDEO_ALL_TAB, userPermissions),
  [VIDEO_TABS_ENUM.own]: hasPermission(VIDEO_MY_TAB, userPermissions),
  [VIDEO_TABS_ENUM.shared]: hasPermission(VIDEO_SHARED_TAB, userPermissions),
});

export const getVideoTabs = (userPermissions) => {
  const availableTabs = getTabsByPermissions(userPermissions);
  const tabs = filterConfig.videoTabs.filters;
  const tabsWithOriginalIndex = tabs.map((tab, index) => ({
    ...tab,
    originalIndex: index,
  }));
  const tabsByPermissions = tabsWithOriginalIndex.filter((tab) => availableTabs[tab.value]);

  return tabsByPermissions;
};

export const getTabDefaultValue = (tabCounters, userPermissions) => {
  const availableTabs = getVideoTabs(userPermissions);
  const { own, shared } = tabCounters;
  let tabDefaultValue = VIDEO_TABS_ENUM.all;

  if (availableTabs.length === 1) {
    tabDefaultValue = availableTabs[0].value;
  } else if (own > 0) {
    tabDefaultValue = VIDEO_TABS_ENUM.own;
  } else if (shared > 0) {
    tabDefaultValue = VIDEO_TABS_ENUM.shared;
  }

  return tabDefaultValue;
};

export const getDefaultTab = (tabCounters, userPermissions) => {
  const availableTabs = getVideoTabs(userPermissions);
  const tabDefaultValue = getTabDefaultValue(tabCounters, userPermissions);

  return availableTabs.find((tab) => tab.value === tabDefaultValue);
};

export const getDefaultTabAfterSearchOrFilter = (userPermissions) => {
  const availableTabs = getVideoTabs(userPermissions);
  const defaultTab = availableTabs[0];

  return defaultTab;
};

export default getVideoTabs;
