import { alert, confirm } from '../js/dialogs.js'

export default {
  props: ['rows', 'currentRow'],
  mounted: function () {
    window.addEventListener('keydown', this.onkey)
  },
  destroyed: function () {
    window.removeEventListener('keydown', this.onkey)
  },
  methods: {
    onkey: function (event) {
      if (this.$refs.table) {
        if (this.$refs.table.contains(document.activeElement)) {
          if ((event.keyCode == 38) || (event.keyCode == 40) ) {
            if (document.activeElement.localName == "select")
            {
              return
            }
    
            if (this.currentRow) {
              let index = this.rows.indexOf(this.currentRow)
    
              if (event.keyCode == 38) { // Up
                if (index > 0) {
                  index = index-1
                }
              }
    
              if (event.keyCode == 40) { // Down
                if (index < this.rows.length-1) {
                  index = index+1
                }      
              }
              this.$emit('set', this.rows[index])
            }
          }
        }
      }

    },
    setCurrentRow(row) {
      if (this.currentRow != row) {
        this.$emit('set', row)
      }
    },
    setFocus() {
      if (this.$refs){
        let index = this.rows.indexOf(this.currentRow)
        if (index > -1) {
          if (this.$refs[this.currentField]) {
            if (typeof this.$refs[this.currentField][index] != 'undefined') {
              this.$refs[this.currentField][index].focus()
            }
          }
        }
      }
    },
    intValidate: function(row, name) {
      if (typeof row[name] == 'string') {
        row[name] = row[name].replace(/[^0-9\-]/g, '')
      }
    },
    floatValidate: function(row, name) {
      if (typeof row[name] == 'string') {
        row[name] = row[name].replace(',', '.')
        row[name] = row[name].replace('..', '.')
        row[name] = row[name].replace(/[^0-9\.\-]/g, '')
      }
    },

    array_move: function (arr, old_index, new_index) {
        if (new_index >= arr.length) {
            var k = new_index - arr.length + 1;
            while (k--) {
                arr.push(undefined);
            }
        }
        arr.splice(new_index, 0, arr.splice(old_index, 1)[0])
      },
      rowUp(array, row) {
        let index = array.indexOf(row)
        if (index > 0) {
            this.array_move(array, index, index-1)
        }
      },
      rowDown(array, row) {
        let index = array.indexOf(row)
        if (index < array.length-1) {
            this.array_move(array, index, index+1)
        }
      },
      rowDelete(array, row) {
        confirm('Do you really want to delete?', 'Confirm').then((res)=> {
          if (res == true) {
            let index = array.indexOf(row)
            array.splice(index, 1)
          }
        })
      },

  },
  watch: {
    currentRow() {
      this.setFocus()
    }
  }
}
