

function transform (item) {
  const newItem = {...item}
  newItem.ts0 = new Date(newItem.ts0);
  newItem.ts1 = new Date(newItem.ts1);
  return newItem;
}

// ATTENTION: This relies on the new planner endpoint
// as per issue #281.

function setRemarks (state, remarks) {
  state.remarks = remarks;
}

function setSequence (state, sequence) {
  state.sequences.push(Object.freeze(transform(sequence)));
}

function deleteSequence (state, sequence) {
  const seq = transform(sequence)
  const idx = state.sequences?.findIndex( s => Object.keys(seq).every( k => JSON.stringify(s[k]) == JSON.stringify(seq[k]) ));
  if (idx != -1) {
    state.sequences.splice(idx, 1)
  }
}

function replaceSequence (state, [oldSequence, newSequence]) {
  console.log("replaceSequence", oldSequence, newSequence);
  const seq = transform(oldSequence)
  const idx = state.sequences?.findIndex( s => Object.keys(seq).every( k => JSON.stringify(s[k]) == JSON.stringify(seq[k]) ));
  console.log("idx", idx);
  if (idx != -1) {
    state.sequences.splice(idx, 1, transform(newSequence))
    console.log("spliced in");
  }
}

function setPlan (state, plan) {
  // We don't need or want the planned sequences array to be reactive
  state.sequences = [];
  plan.sequences.forEach( sequence => setSequence(state, sequence) );
  setRemarks(state, plan.remarks);
}

function setPlanLoading (state, abortController = new AbortController()) {
  state.loading = abortController;
}

// This assumes that we know any transactions have finished or we
// don't care about aborting.
function clearPlanLoading (state) {
  state.loading = null;
}

function setPlanTimestamp (state, timestamp = new Date()) {
  // NOTE: There is no `modified_on` property in the plan
  // result or in the database schema, but we should probably add
  // one.
  if (timestamp === true) {
    const tstamp = state.plan
      .map( item => item.modified_on )
      .reduce( (acc, cur) => acc > cur ? acc : cur );
    state.timestamp = tstamp ? new Date(tstamp) : new Date();
  } else {
    state.timestamp = timestamp;
  }
}

function setPlanETag (state, etag) {
  state.etag = etag;
}

function abortPlanLoading (state) {
  if (state.loading) {
    state.loading.abort();
  }
  state.loading = null;
}

export default {
  setRemarks,
  setSequence,
  deleteSequence,
  replaceSequence,
  setPlan,
  setPlanLoading,
  clearPlanLoading,
  setPlanTimestamp,
  setPlanETag
};
