<template>
  <v-row no-gutters>
    <v-col cols="12" sm="12">
      <v-card class="pa-2 ma-2" variant="outlined" >
        <v-card-title>ATEM Keyer Synchronization Settings</v-card-title>
        <v-container>
          <v-card elevation="1" v-for="item in this.keySyncItems" :key="item.id">
            <v-row>
              <v-col cols="6">
                <v-list two-line> <!-- subheader -->
                  <!-- <v-subheader>Source</v-subheader> -->
                  <v-list-item>
                      <v-list-item-title>{{ getDeviceDisplay(item.source.deviceId)}}</v-list-item-title>
                      <v-list-item-subtitle>Source Device</v-list-item-subtitle>
                  </v-list-item>
                  <v-list-item>
                      <v-list-item-title>{{ getDeviceKeyDisplay(item.source.deviceId, item.source.keyId)}}</v-list-item-title>
                      <v-list-item-subtitle>Source Keyer</v-list-item-subtitle>
                  </v-list-item>
                  <v-list-item>
                      <v-list-item-title>
                        <v-btn icon="mdi-pencil" title="Edit" size="small" variant="outlined"  @click="edit(item.id)" />
                      </v-list-item-title>
                      <v-list-item-subtitle></v-list-item-subtitle>
                  </v-list-item>
                </v-list>
              </v-col>
              <v-col cols="6">
                <v-table>
                  <template v-slot:default>
                      <thead>
                        <tr>
                            <th class="text-left">Destination Device</th>
                            <th class="text-left">Destination Keyer</th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr v-for="dest in item.destinations" :key="dest.id">
                            <td>{{ getDeviceDisplay(dest.deviceId)}}</td>
                            <td>{{ getDeviceKeyDisplay(dest.deviceId, dest.keyId)}}</td>
                        </tr>
                      </tbody>
                  </template>
                </v-table>
              </v-col>
            </v-row>
          </v-card>
          <v-row>
            <v-col cols="12">
              <v-btn icon="mdi-plus" title="Add item" size="small" variant="outlined"  @click="edit('')" />
            </v-col>
          </v-row>
          <v-dialog v-model="editDialog.show" max-width="600">
            <v-card>
              <v-card-title class="headline">Editor</v-card-title>
              <v-card-text>
                <v-form @submit="save(editDialog.id)">
                  <v-select v-model="editDialog.source.deviceId" :items="atemDevices" item-value="config.id" item-title="config.name" label="Source Device" />
                  <v-select :disabled="!editDialog.source.deviceId" v-model="editDialog.source.keyId" :items="editSourceDeviceParams.keys" item-value="id" item-title="label" label="Source Keyer" />
                  <v-table>
                    <template v-slot:default>
                        <thead>
                          <tr>
                              <th class="text-left">Destination Device</th>
                              <th class="text-left">Destination Keyer</th>
                              <th class="text-left"></th>
                          </tr>
                        </thead>
                        <tbody>
                          <tr v-for="dest in editDialog.destinations" :key="dest.id">
                              <td>{{ getDeviceDisplay(dest.deviceId)}}</td>
                              <td>{{ getDeviceKeyDisplay(dest.deviceId, dest.keyId)}}</td>
                              <td><v-btn color="red darken-1" icon="mdi-delete" title="Delete destination" size="small" variant="outlined"  @click="removeEditDestination(dest.deviceId, dest.keyId)" /></td>
                          </tr>
                          <tr>
                            <td><v-select :disabled="!editDialog.source.keyId" v-model="editDialog.newDestDeviceId" :items="atemDevices" item-value="config.id" item-title="config.name" label="New Device" /></td>
                            <td><v-select :disabled="!editDialog.newDestDeviceId" v-model="editDialog.newDestKeyId" :items="editDestinationDeviceKeys" item-value="id" item-title="label" label="New Keyer" /></td>
                            <td><v-btn color="darken-1" title="Add destination" icon="mdi-plus" :disabled="!editDialog.newDestKeyId" size="small" variant="outlined" @click="addEditDestination()" /></td>
                          </tr>
                        </tbody>
                    </template>
                  </v-table>
                </v-form>
              </v-card-text>
              <v-card-actions>
                <v-btn color="red darken-1" text @click="remove(editDialog.id); editDialog.show = false" v-if="editDialog.id">Delete</v-btn>
                <v-spacer></v-spacer>
                <v-btn color="darken-1" text @click="editDialog.show = false">Cancel</v-btn>
                <v-btn color="green darken-1" text @click="save(editDialog.id); editDialog.show = false">OK</v-btn>
              </v-card-actions>
            </v-card>
          </v-dialog>
        </v-container>
      </v-card>
    </v-col>
  </v-row>
</template>

<script>
// @ is an alias to /src

const defaultEditDialogParams = {
  show: false,
  id: '',
  source: { deviceId: '', keyId: '' },
  destinations: [],
  newDestDeviceId: '',
  newDestKeyId: ''
}

export default {
  name: 'atem-keysync',
  components: {
  },
  data () {
    return {
      // keySyncItems: [
      //   {
      //     id: '123',
      //     source: { deviceId: 'PQNxd574', keyId: 'dsk1'},
      //     destinations: [
      //       { deviceId: 'PQNxd574', keyId: 'me0_key0', id: '123456' },
      //       { deviceId: 'PQNxd574', keyId: 'dsk2', id: '1234567' }
      //     ]
      //   }
      // ],
      editDialog: {
        ...defaultEditDialogParams
      }
    }
  },
  computed: {
    keySyncItems() { return this.$store.state.keySync },
    atemDevices() { return this.$store.state.devices.filter(d => d && d.config.type === 'ATEM') },
    editSourceDeviceParams() {
      const device = this.atemDevices.find(d => d && d.config.id === this.editDialog.source.deviceId)
      if (device && device.params) return device.params
      return {}
    },
    editDestinationDeviceKeys() {
      const device = this.atemDevices.find(d => d && d.config.id === this.editDialog.newDestDeviceId)
      if (device && device.params) {
        const keys = device.params.keys.filter(k => this.editDialog.destinations.find(x => (x.deviceId === device.config.id && x.keyId === k.id)) === undefined && (this.editDialog.source.deviceId !== device.config.id || this.editDialog.source.keyId !== k.id))
        return keys
      }
      return []
    }
  },
  methods: {
    getDeviceDisplay(deviceId) {
      const device = this.atemDevices.find(d => d && d.config.id === deviceId)
      if (device) {
        return device.config.name
      }
      return `Unknown (${deviceId})`
    },
    getDeviceKeyDisplay(deviceId, keyId) {
      const device = this.atemDevices.find(d => d && d.config.id === deviceId)
      if (device) {
        const key = device.params.keys.find(k => k.id === keyId)
        if (key) {
          return key.label
        }
      }
      return `Unknown (${deviceId}, ${keyId})`
    },
    edit(syncId) {
      Object.assign(this.editDialog, defaultEditDialogParams)
      const settings = this.keySyncItems.find(s => s.id === syncId)
      if (settings) {
        Object.assign(this.editDialog, JSON.parse(JSON.stringify(settings)))
      }
      this.editDialog.show = true
    },
    save(syncId) {
      this.$socket.emit('setKeySync', { 
          id: this.editDialog.id,
          source: {...this.editDialog.source},
          destinations: JSON.parse(JSON.stringify(this.editDialog.destinations))
        })
    },
    remove(syncId) {
      this.$socket.emit('deleteKeySync', { id: syncId })
    },
    removeEditDestination(deviceId, keyId) {
      const dest = this.editDialog.destinations.find(d => d.deviceId === deviceId && d.keyId === keyId)
      if (dest) {
        const index = this.editDialog.destinations.indexOf(dest)
        if (index >= 0) {
          this.editDialog.destinations.splice(index, 1)
        }
      }
    },
    addEditDestination() {
      const device = this.atemDevices.find(d => d && d.config.id === this.editDialog.newDestDeviceId)
      if (device) {
        const key = device.params.keys.find(k => k.id === this.editDialog.newDestKeyId)
        if (key) {
          this.editDialog.destinations.push({ deviceId: device.config.id, keyId: key.id, id: (device.config.id + '_' + key.id) })
          this.editDialog.newDestDeviceId = ''
          this.editDialog.newDestKeyId = ''
        }
      }
    }
  }
}
</script>
