import { OverlapType, getOverlapType } from '../getOverlapType';
import {
  getSelectedClips,
  getSelectionEndBeats,
  getSelectionStartBeats,
} from '../selectors';
import { StudioProjectState } from '../types';
import updateClips from './updateClips';

export default function toggleClipFade(
  state: StudioProjectState
): StudioProjectState {
  const selectedClips = getSelectedClips(state);
  const selectionStartBeats = getSelectionStartBeats(state);
  const selectionEndBeats = getSelectionEndBeats(state);
  const clipsWithStartSelected = selectedClips.filter((clip) =>
    [OverlapType.SelectionStartsWithin].includes(
      getOverlapType(
        selectionStartBeats,
        selectionEndBeats,
        clip.startBeats,
        clip.endBeats
      )
    )
  );

  const clipsWithEndSelected = selectedClips.filter((clip) =>
    [OverlapType.SelectionEndsWithin].includes(
      getOverlapType(
        selectionStartBeats,
        selectionEndBeats,
        clip.startBeats,
        clip.endBeats
      )
    )
  );

  const startsUpdated = updateClips(
    clipsWithStartSelected.map((clip) => clip.id),
    (clip) => {
      const fadeInBeats = selectionEndBeats - clip.startBeats;
      return {
        ...clip,
        fadeInBeats: clip.fadeInBeats === fadeInBeats ? 0 : fadeInBeats,
      };
    }
  )(state);

  const endsUpdated = updateClips(
    clipsWithEndSelected.map((clip) => clip.id),
    (clip) => {
      const fadeOutBeats = clip.endBeats - selectionStartBeats;
      return {
        ...clip,
        fadeOutBeats: clip.fadeOutBeats === fadeOutBeats ? 0 : fadeOutBeats,
      };
    }
  )(startsUpdated);

  return endsUpdated;
}
