<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";

  let error = null;
  let name = "";
  let fromStr = dateStr(new Date())
  let toStr = dateStr(new Date(Date.now() + (86400000 * 6)))
  let tagsStr = "";

  function createPeriod() {
    const from = new Date(`${fromStr} 00:00:00.000`);
    const to = new Date(`${toStr} 23:59:59.999`);
    const tags = tagsStr.split(",").map(t => t.trim()).filter(t => t.length > 0);

    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.createPeriod({name, from, to, tags}).then(() => {
      modal.close();
    }).catch(err => {
      error = err.message || err;
      console.warn(err);
    });
  }
</script>

<ModalFrame title="Create Period" error={error} closable on:close={() => modal.close()}>
  <form on:submit|preventDefault={() => createPeriod()}>
    <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} />
    <label>Tags (Comma separated)</label>
    <input type="text" bind:value={tagsStr} />
    <button type="submit">Create</button>
  </form>
</ModalFrame>