<template>
  <div :class="[componentClass]">
    <input type="checkbox" :id="rowId(rowIndex)" v-on:change="onSelectedRowValueChange($event)" :checked="isChecked">
    <label class="c-checkbox" :for="rowId(rowIndex)" />
  </div>
</template>

<script>

import base from './c-base'
import { mapActions } from 'vuex'

export default {
  extends: base,
  data: function () {
    return {
      componentClass: 'c-rowcheck'
    }
  },
  props: {
    rowIndex: {
      type: Number
    }
  },
  computed: {
    isChecked: function () {
      return this.dataSet.keyFieldsIdents &&
       this.dataSet.keyFieldsIdents.length > 0 && 
       this.dataSet.selectedRows.find(item => {
        let result = true
        this.dataSet.keyFieldsIdents.forEach(keyField => {
          result = result && this.contextRow[keyField.dataFieldIdent] === item[keyField.dataFieldIdent]
        })
        return result
        }) ? true : false
    }
  },
  methods: {
    ...mapActions('csAppWindowsUtils', [
      'addSelectedRow',
      'deleteSelectedRow'
    ]),
    rowId: function (rowIndex) {
      return (this.componentId + '.' + rowIndex)
    },
    onSelectedRowValueChange: async function (evt) {
      let payload = {
        appWindowIdent: this.appWindowIdent,
        dataSetIdent: this.dataSetIdent,
        row: this.contextRow
      }
      let result = 0
      if (evt.target.checked) result = await this.addSelectedRow(payload)
      if (!evt.target.checked) await this.deleteSelectedRow(payload)
      if (result === -1) {
        evt.target.checked = false
      }
      
    }
  }
}</script>

