import dayjs from 'dayjs';
export function findConflicts(schedule, object) {
  const conflicts: any = [];
  schedule.forEach(item => {
    item.weeks = getLoopsForTheOnceItem(item);
  });
  object.weeks = getLoopsForTheOnceItem(object);
  const objectStart = object.isSleep
    ? object.time[0] * 60 + object.time[1]
    : object.time[0] * 60 + object.time[1] - object.fade;
  const objectEnd = object.isSleep
    ? objectStart + object.fade
    : object.time[0] * 60 + object.time[1];
  for (let i = 0; i < schedule.length; i++) {
    const { enable, weeks, time, fade, isSleep } = schedule[i];
    if (enable === 0) continue;

    const start = isSleep ? time[0] * 60 + time[1] : time[0] * 60 + time[1] - fade;
    const end = isSleep ? start + fade : time[0] * 60 + time[1];

    let conflict = false;
    for (let j = 0; j < 7; j++) {
      if (weeks[j] && start < 0 && object.weeks[j - 1 < 0 ? 6 : j - 1]) {
        if (objectEnd - 24 * 60 > start) {
          conflict = true;
          break;
        }
      }
      if (object.weeks[j] && weeks[j]) {
        if (objectStart < end && objectEnd > start) {
          conflict = true;
          break;
        }
      }
      if (weeks[j] && end > 24 * 60 && object.weeks[j + 1 > 6 ? 0 : j + 1]) {
        if (end - 24 * 60 > objectStart) {
          conflict = true;
          break;
        }
      }
    }

    if (conflict) {
      conflicts.push(schedule[i]);
    }
  }

  return conflicts;
}
// once
function isLoopsEqualToOnce(loops) {
  return loops.every(item => item === 0 || item === '0');
}

function getLoopsForTheOnceItem(item) {
  let newLoops = [...item.loops];
  if (isLoopsEqualToOnce(newLoops)) {
    const now = dayjs();
    newLoops[now.day()] = 1;
  }
  return newLoops;
}
