<script setup>
  import { presetRuleset, initialStates } from "../modules/preset.js";
  import { globalStore } from "../stores/index.js";
  import MenuRow from "./MenuRow.vue";

  const store = globalStore();

  const copyRuleset = () => {
    const newRuleset = JSON.stringify(store.ruleset1d);
    navigator.clipboard.writeText(newRuleset);
  };

  const updateSingleRule = (event) => {
    const elem = event.target;
    const value = elem.checked ? 1 : 0;
    store.ruleset1d.rules[elem.name] = value;
  };

  const updateRuleset = (event) => {
    const elem = event.target;
    const name = elem.value;
    const newRuleset = presetRuleset.find((ruleset) => {
      return ruleset.name === name;
    });
    store.ruleset1d = newRuleset;
  };

  const updateInitialState = (event) => {
    const elem = event.target;
    store.initial1dState = elem.value;
  };
</script>

<template>
  <MenuRow row-title="Elementary Automaton">
    <form>
      <div class="form-field">
        <input
          type="button"
          name="start"
          value="start"
          @click="store.toggleDraw1d()"
        />
      </div>
      <div class="form-field">
        <label>
          Initial state presets
          <br />
          <select
            name="initialStates"
            :value="store.initial1dState"
            @input="updateInitialState"
          >
            <option
              v-for="(state, index) in initialStates"
              :key="'initial-state-elementary' + index"
              :value="state.id"
            >
              {{ state.name }}
            </option>
          </select>
        </label>
      </div>
      <div class="form-field">
        <label>Rules</label>
      </div>
      <div class="form-field">
        <label
          >Rules presets
          <br />
          <select
            name="ruleset-elementary"
            :value="store.ruleset1d.name"
            @input="updateRuleset"
          >
            <option
              v-for="(ruleset, index) in presetRuleset"
              :key="'ruleset-preset-elementary-' + index"
              :value="ruleset.name"
            >
              {{ ruleset.name }}
            </option>
          </select>
        </label>
      </div>
      <div class="form-field">
        <a style="cursor: pointer" @click="copyRuleset">copy rules</a>
      </div>
      <div
        v-for="(rule, name, index) in store.ruleset1d.rules"
        :key="'rule-' + index"
        class="form-field"
      >
        <label
          >{{ name }}
          <input
            :value="rule"
            type="checkbox"
            :name="name"
            :checked="rule"
            @input="updateSingleRule"
          />
        </label>
      </div>
    </form>
  </MenuRow>
</template>
