import clearTimeFromTrack from '../actionHelpers/clearTimeFromTrack';
import {
  getDerivedTiming,
  getFocusedClipCreationIntent,
  getSelectionEndBeats,
  getSelectionStartBeats,
} from '../selectors';
import { StudioProjectState } from '../types';

export default function deleteTimelineSelection(
  state: StudioProjectState
): StudioProjectState {
  const focusedClipCreationIntent = getFocusedClipCreationIntent(state);
  if (focusedClipCreationIntent) {
    return {
      ...state,
      metadata: {
        ...state.metadata,
        usedDelete: true,
      },
      tracks: state.tracks.map((track) =>
        track.clipCreationIntents.find(
          (c) => c.id === focusedClipCreationIntent.id
        )
          ? {
              ...track,
              clipCreationIntents: track.clipCreationIntents.filter(
                (c) => c.id !== focusedClipCreationIntent.id
              ),
            }
          : track.takeLanes.find((tl) =>
                tl.clipCreationIntents.find(
                  (c) => c.id === focusedClipCreationIntent.id
                )
              )
            ? {
                ...track,
                takeLanes: track.takeLanes.map((tl) => {
                  if (
                    tl.clipCreationIntents.find(
                      (c) => c.id === focusedClipCreationIntent.id
                    )
                  ) {
                    return {
                      ...tl,
                      clipCreationIntents: tl.clipCreationIntents.filter(
                        (c) => c.id !== focusedClipCreationIntent.id
                      ),
                    };
                  }
                  return tl;
                }),
              }
            : track
      ),
    };
  }
  return {
    ...state,
    metadata: {
      ...state.metadata,
      [getSelectionStartBeats(state) === getSelectionEndBeats(state)
        ? 'usedSplit'
        : 'usedDelete']: true,
    },
    tracks: state.tracks.map((track) => {
      let newTrack = track;
      if (state.selection.trackIds.includes(track.id)) {
        newTrack = clearTimeFromTrack(
          getDerivedTiming(state),
          getSelectionStartBeats(state),
          getSelectionEndBeats(state),
          track
        );
      }
      if (
        newTrack.takeLanes.find((tl) =>
          state.selection.trackIds.includes(tl.id)
        )
      ) {
        newTrack = {
          ...newTrack,
          takeLanes: newTrack.takeLanes.map((tl) =>
            state.selection.trackIds.includes(tl.id)
              ? clearTimeFromTrack(
                  getDerivedTiming(state),
                  getSelectionStartBeats(state),
                  getSelectionEndBeats(state),
                  tl
                )
              : tl
          ),
        };
      }
      return newTrack;
    }),
    selection: {
      ...state.selection,
      focusedArea: 'timeline',
    },
  };
}
