import { createMachine, interpret } from "xstate";
import { getPlans, setPlan, getChecks, recordCheck } from '@/services/trackTimeDuration'

export const machine = createMachine(
  {
    id: "trackTime",
    initial: "choose",
    context: {
      hi: 'hi'
    },
    states: {
      choose: {
        on: {
          SLEEPING: {
            target: "sleeping",
          },
          MIXED: {
            target: "mixed",
          },
          FAST: {
            target: "fasting",
          },
        },
      },
      sleeping: {
        initial: "WAIT_TO_START",
        states: {
          WAIT_TO_START: {
            on: {
              start: {
                target: "ON_GOING",
              },
            },
          },
          ON_GOING: {
            on: {
              end: {
                target: "DONE",
              },
            },
          },
          DONE: {},
        },
      },
      mixed: {
        initial: "WAIT_TO_START",
        states: {
          WAIT_TO_START: {
            on: {
              start_fast: {
                target: "ON_GOING1",
              },
            },
          },
          ON_GOING1: {
            on: {
              "start_sleep": {
                target: "ON_GOING2",
              },
              "end fast(skip_start_sleep)": {
                target: "DONE",
              },
            },
          },
          ON_GOING2: {
            on: {
              "end fast(skip_end_sleep)": {
                target: "DONE",
              },
              "end_sleep": {
                target: "ON_GOING3",
              },
            },
          },
          DONE: {},
          ON_GOING3: {
            on: {
              end_fast: {
                target: "DONE",
              },
            },
          },
        },
      },
      fasting: {
        initial: "WAIT_TO_START",
        states: {
          WAIT_TO_START: {
            on: {
              start: {
                target: "ON_GOING",
              },
            },
          },
          ON_GOING: {
            on: {
              end: {
                target: "DONE",
              },
            },
          },
          DONE: {},
        },
      },
    },
    schema: {
      events: {} as
        | { type: "end" }
        | { type: "FAST" }
        | { type: "MIXED" }
        | { type: "start" }
        | { type: "SLEEPING" }
        | { type: "end_fast" }
        | { type: "end_sleep" }
        | { type: "start_fast" }
        | { type: "start_sleep" }
        | { type: "end fast(skip_end_sleep)" }
        | { type: "end fast(skip_start_sleep)" }
        | { type: "GET_STATUS"}
    },
    predictableActionArguments: true,
    preserveActionOrder: true,
  },
  {
    actions: {},
    services: {
      getPlans, setPlan, getChecks, recordCheck
    },
    guards: {},
    delays: {},
  },
);

const service = interpret(machine).start();

export default service;