import { stableSegmentStateKey } from './segment-state.js';

function cloneJson(value) {
  return value == null ? null : JSON.parse(JSON.stringify(value));
}

export function createSegmentClipboardPayload({
  track,
  trackId,
  index,
  segment,
  keyframeData,
  curveTypes,
  lfoData,
  exposedParams,
  exposedParamsMeta,
}) {
  const key = stableSegmentStateKey(track, trackId, segment, index);
  return {
    track,
    trackId,
    segment: cloneJson(segment),
    keyframes: cloneJson(keyframeData[key]),
    curveTypes: cloneJson(curveTypes[key]),
    lfoData: cloneJson(lfoData[key]),
    exposedParams: exposedParams[key] ? [...exposedParams[key]] : null,
    exposedParamsMeta: cloneJson(exposedParamsMeta[key]),
  };
}

export function applySegmentClipboardState(payload, targetKey, stores) {
  const mappings = [
    ['keyframes', stores.keyframeData, false],
    ['curveTypes', stores.curveTypes, false],
    ['lfoData', stores.lfoData, false],
    ['exposedParams', stores.exposedParams, true],
    ['exposedParamsMeta', stores.exposedParamsMeta, false],
  ];
  for (const [payloadKey, store, asSet] of mappings) {
    if (payload[payloadKey] == null) continue;
    store[targetKey] = asSet
      ? new Set(payload[payloadKey])
      : cloneJson(payload[payloadKey]);
  }
}

export function handleSegmentClipboardShortcut(event, {
  editorMode,
  selectedSegment,
  clipboardSegment,
  copy,
  cut,
  paste,
  notify = () => {},
}) {
  if (!(event.ctrlKey || event.metaKey) || event.shiftKey || editorMode !== 'timeline') {
    return false;
  }

  let action = null;
  let message = '';
  if (event.code === 'KeyC' && selectedSegment) {
    action = copy;
    message = 'Copied to clipboard';
  } else if (event.code === 'KeyX' && selectedSegment) {
    action = cut;
    message = 'Cut to clipboard';
  } else if (event.code === 'KeyV' && clipboardSegment) {
    action = paste;
    message = 'Pasted from clipboard';
  }
  if (!action) return false;

  event.preventDefault();
  if (action()) notify(message);
  return true;
}
