<script>
  import pluralize from "pluralize";
  import ModalFrame from "../components/ModalFrame";
  import SubGoalInput from "../components/SubGoalInput";

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

  export let period = {};

  let error = null;
  let activityId = "";
  let pointCount = "1000";

  function addPeriodGoal() {
    error = null;

    const parsedPointCount = parseInt(pointCount)
    if (Number.isNaN(parsedPointCount)) {
      error = "Point count must be a number.";
      return
    }
    if (parsedPointCount <= 0 || (parsedPointCount % 1000) !== 0) {
      error = "Point must be a positive non-zero multiple of 1000.";
      return
    }

    const addGoal = {
      activityId: activityId,
      pointCount: parsedPointCount,
    }

    stufflog.updatePeriod(period.id, {addGoal}).then(() => {
      modal.close();
    }).catch(err => {
      error = err.message || err;
      console.warn(err);
    });
  }

  $: if (activityId === "" && $stufflog.activities.length > 0) {
    activityId = $stufflog.activities[0].id;
  }
</script>

<ModalFrame title={`Add ${period.name} Goal`} error={error} closable on:close={() => modal.close()}>
  <form on:submit|preventDefault={() => addPeriodGoal()}>
    <label>Activity</label>
    <select bind:value={activityId}>
      {#each $stufflog.activities as activity (activity.id)}
        <option value={activity.id}>{activity.name}</option>
      {/each}
    </select>
    <label>Points</label>
    <input class="nolast" type="string" bind:value={pointCount} />

    <p>
      The amount of points must be in an increment of 1000, which should be
      equivalent to about an hour of baseline activity. Subgoal values are 
      multipliers. 1.05 means that the 5% more points are added. 0.5 means 
      the points are halved.
    </p>

    <hr />

    <button type="submit">Add Goal</button>
  </form>
</ModalFrame>

<style>
  p {
    margin-top: 1em;
  }
</style>