import {
  CHAPTER_DESCRIPTION_TYPE,
  CHAPTER_TITLE_TYPE,
  CONTENT_TYPE,
  OBJECTIVE_GROUP_TYPE,
  OBJECTIVE_TYPE
} from '@/consts/types';
import CHANGE_CONTENT_BLOCK_MUTATION from '@/graphql/gql/mutations/mutateContentBlock.gql';
import UPDATE_OBJECTIVE_VISIBILITY_MUTATION from '@/graphql/gql/mutations/updateObjectiveVisibility.gql';
import UPDATE_OBJECTIVE_GROUP_VISIBILITY_MUTATION from '@/graphql/gql/mutations/updateObjectiveGroupVisibility.gql';
import UPDATE_CHAPTER_VISIBILITY_MUTATION from '@/graphql/gql/mutations/updateChapterVisibility.gql';

export const createVisibilityMutation = (type, id, visibility) => {
  let mutation, variables;
  switch (type) {
    case CONTENT_TYPE:
      mutation = CHANGE_CONTENT_BLOCK_MUTATION;
      variables = {
        input: {
          id,
          contentBlock: {
            visibility
          }
        }
      };
      break;
    case OBJECTIVE_TYPE:
      mutation = UPDATE_OBJECTIVE_VISIBILITY_MUTATION;
      variables = {
        input: {
          id,
          visibility
        }
      };
      break;
    case OBJECTIVE_GROUP_TYPE:
      mutation = UPDATE_OBJECTIVE_GROUP_VISIBILITY_MUTATION;
      variables = {
        input: {
          id,
          visibility
        }
      };
      break;
    case CHAPTER_TITLE_TYPE:
    case CHAPTER_DESCRIPTION_TYPE:
      mutation = UPDATE_CHAPTER_VISIBILITY_MUTATION;
      variables = {
        input: {
          id,
          type,
          visibility
        }
      };
      break;
  }

  return {
    mutation,
    variables
  };
};

const containsClass = (arr = [], schoolClass) => arr.map(entry => entry.id).includes(schoolClass.id);

export const hidden = ({
                         type,
                         block: {
                           userCreated,
                           visibleFor,
                           hiddenFor,
                           titleHiddenFor,
                           descriptionHiddenFor,
                           hidden
                         },
                         schoolClass
                       }) => {
  if (hidden === true) {
    return true;
  }
  switch (type) {
    case CONTENT_TYPE:
    case OBJECTIVE_TYPE:
      // is this content block / objective group user created?
      return userCreated
        // if so, is visibility not explicitly set for this school class?
        ? !containsClass(visibleFor, schoolClass)
        // otherwise, is it explicitly hidden for this school class?
        : containsClass(hiddenFor, schoolClass);
    case OBJECTIVE_GROUP_TYPE:
      return containsClass(hiddenFor, schoolClass);
    case CHAPTER_TITLE_TYPE:
      return containsClass(titleHiddenFor, schoolClass);
    case CHAPTER_DESCRIPTION_TYPE:
      return containsClass(descriptionHiddenFor, schoolClass);
    default:
      return false;
  }
};
