<template>
  <main id="main">
    <canvas
      id="canvas"
      ref="canvas"
      width="500"
      height="500"
    />
  </main>
</template>
<script>
import { initialState1d, createBoard } from '../modules/automata.js'
import { getRandomInt } from '../modules/common.js'
export default {
  name: 'Canvas',
  data() {
    return {
      canvas: null,
      ctx: null
    }
  },
  computed: {
    cellProperties() {
      return this.$store.state.cellProperties
    },
    rules() {
      return this.$store.state.rules1d
    }
  },
  mounted() {
    this.canvas = this.$refs['canvas']
    this.canvas.width = 1280
    this.canvas.height = 720
    this.context = this.canvas.getContext('2d')
    this.$root.$on('draw1d', () => { this.draw1d() })
  },
  methods: {
    drawCanvas(board) {
      const props = this.CellProperties;
      board.map((row, y) => {
        const d = props.size;
        return row.map(
          (cell, x) => {
            this.ctx.fillStyle = (
              () => {
                if (cell === 1) return props.liveColor;
                return props.deadColor;
              })();
            this.ctx.fillRect(x * d, y * d, d, d);
            return cell;
          },
        );
      });
    },
    draw1d() {
      const rules = this.rules;
      const props = this.CellProperties;
      console.log(props.size)
      const initialState = initialState1d(
        Math.floor(this.canvas.width / props.size),
        getRandomInt,
        [0, 2],
      );
      const board = createBoard(
        initialState,
        rules,
        Math.floor(this.canvas.height / props.size));
      this.drawCanvas(board);
    }
  }
}
</script>

