<script>
  import ModalFrame from "../components/ModalFrame";
  import ActivityIconSelect from "../components/ActivityIconSelect";

  import modal from "../stores/modal";
  import stufflog from "../stores/stufflog";

  import dateStr from "../utils/dateStr";

  export let period = {};

  let error = null;
  let name = period.name;
  let fromStr = dateStr(period.from)
  let toStr = dateStr(period.to)

  function editPeriod() {
    const from = new Date(`${fromStr} 00:00:00.000`);
    const to = new Date(`${toStr} 23:59:59.999`);

    error = null;

    if (Number.isNaN(from.getTime())) {
      error = "You must enter a from date.";
      return;
    }
    if (Number.isNaN(from.getTime())) {
      error = "You must enter a to date.";
      return;
    }

    stufflog.updatePeriod(period.id, {setName: name, setFrom: from, setTo: to}).then(() => {
      modal.close();
    }).catch(err => {
      error = err.message || err;
      console.warn(err);
    });
  }
</script>

<ModalFrame title="Edit Period" error={error} closable on:close={() => modal.close()}>
  <form on:submit|preventDefault={() => editPeriod()}>
    <label>Name</label>
    <input type="text" bind:value={name} />
    <label>From</label>
    <input type="date" bind:value={fromStr} />
    <label>To</label>
    <input type="date" bind:value={toStr} />
    <button type="submit">Save</button>
  </form>
</ModalFrame>