<template>
    <v-row no-gutters>
      <v-col cols="12" sm="12">
        <v-card class="pa-2 ma-2" variant="outlined" >
            <v-card-title>GPIO Modules</v-card-title>
            <v-table>
            <template v-slot:default>
                <thead>
                <tr>
                    <th class="text-left">Name</th>
                    <th class="text-left">Inputs</th>
                    <th class="text-left">Outputs</th>
                    <th class="text-left">Status</th>
                </tr>
                </thead>
                <tbody>
                <tr v-for="item in boards" :key="item.name">
                    <td>{{ item.name }}</td>
                    <td>
                      <div class="io-overview">
                        <div :class="'io-item ' + (input.value === 1 ? 'active' : '')" v-for="(input, i) in item.inputs" :key="input.id">{{ i }}</div>
                      </div>
                    </td>
                    <td>
                      <div class="io-overview">
                        <div :class="'io-item ' + (output.value === 1 ? 'active' : '')" v-for="(output, i) in item.outputs" :key="output.id"
                           @mousedown.prevent="mousedown(output.id)" @mouseup.prevent="mouseup(output.id)" @mouseleave.prevent="mouseup(output.id)" title="Press to test output" style="cursor:pointer">{{ i }}</div>
                      </div>
                    </td>
                    <td v-if="item.status == 'ok'"><v-icon color="green">mdi-checkbox-blank-circle</v-icon></td>
                    <td v-else><v-icon color="orange">mdi-checkbox-blank-circle-outline</v-icon></td>
                </tr>
                </tbody>
            </template>
            </v-table>
        </v-card>
        
        <v-card class="pa-2 ma-2" variant="outlined" >
            <v-card-title>IP Configuration</v-card-title>
            <v-container>
              <v-form ref="ipConf" v-model="ipConfValid" lazy-validation>
                <v-row>
                  <v-col cols="16">
                    <v-text-field v-model="nwIp" label="IP address" :rules="[rules.required, rules.ip]" ></v-text-field>
                  </v-col>
                  <v-col cols="2">
                    <v-text-field v-model.number="nwNm" label="Netmask" :rules="[rules.nm]"></v-text-field>
                  </v-col>
                </v-row>
                <v-row>
                  <v-col>
                    <v-text-field v-model="nwGw" label="Gateway" :rules="[rules.ip]"></v-text-field>
                  </v-col>
                </v-row>
                <v-row>
                  <v-col>
                    <v-text-field v-model="nwNs" label="Nameserver" :rules="[rules.ip]"></v-text-field>
                  </v-col>
                </v-row>
                <v-row>
                  <v-col>
                    <v-btn color="primary" :disabled="!nwChanged || !ipConfValid" @click.prevent="SaveNwConfig()">Save</v-btn>
                  </v-col>
                </v-row>
              </v-form>
            </v-container>
        </v-card>
        
        <v-card class="pa-2 ma-2" variant="outlined" >            
            <v-card-title>Companion Update</v-card-title>
            <v-container>
              <v-form ref="companionUpdate" v-model="companionUpdateValid" lazy-validation>
                <v-row>
                  <v-col>NOTE: Requires internet connection!</v-col>
                </v-row>
                <v-row>
                  <v-col>
                    <v-text-field v-model="companionVersion" label="New Version" placeholder="v0.0.0" :rules="[rules.required, rules.version]"></v-text-field>
                  </v-col>
                </v-row>
                <v-row>
                  <v-col>
                    <v-btn color="primary" :disabled="!companionUpdateValid" @click.prevent="UpdateCompanion()">Update</v-btn>
                  </v-col>
                </v-row>
                <v-row v-if="companionUpdateResult !== ''">
                  <v-col>
                    <pre>{{ companionUpdateResult }}</pre>
                  </v-col>
                </v-row>
              </v-form>
            </v-container>
        </v-card>
        
        <v-card class="pa-2 ma-2" variant="outlined" >
            <v-card-title>Date &amp; Time</v-card-title>
            <v-container>
                <v-btn color="primary" @click.prevent="SetDateTimeToCurrent()">Set date from browser time</v-btn>
            </v-container>
        </v-card>
        
        <v-card class="pa-2 ma-2" variant="outlined" >
            <v-card-title>Remote Connection</v-card-title>
            <v-container>
              <v-row>
                <v-col>
                  <v-checkbox v-model="remoteConnectionEnabled" label="Enabled" @change="SetRemoteConnection()"></v-checkbox>
                </v-col>
              </v-row>
              <v-row>
                <v-col v-if="remoteConnectionActive"><v-icon color="green">mdi-checkbox-blank-circle</v-icon> Remote connection active</v-col>
                <v-col v-else><v-icon color="orange">mdi-checkbox-blank-circle-outline</v-icon> Remote connection inactive</v-col>
                <v-btn color="secondary" @click.prevent="GetRemoteConnection()">Refresh</v-btn>
              </v-row>
            </v-container>
        </v-card>
        
        <!-- <v-card class="pa-2 ma-2" variant="outlined" >
            <v-card-title>Import</v-card-title>
            <v-container>
                <v-file-input label="Configuration" :disabled="true"></v-file-input>
                <v-btn color="primary" :disabled="true">Import</v-btn>
            </v-container>
        </v-card> -->
        
        <v-card class="pa-2 ma-2" variant="outlined" >
            <v-card-title>Saved configurations</v-card-title>
            <v-container>
              <v-form ref="backup" lazy-validation>
                <v-row>
                    <v-col cols="16">
                      <v-text-field v-model="backupName" label="Backup name" :rules="[rules.required]" ></v-text-field>
                    </v-col>
                    <v-col cols="2" style="vertical-align: middle">
                      <v-btn color="primary" :disabled="!(this.backupName && this.backupName.length > 0)" @click.prevent="DoBackup()">Backup</v-btn>
                    </v-col>
                </v-row>
              </v-form>
              <v-row>
                <v-col>
                  <v-table class="backups-table">
                    <template v-slot:default>
                      <thead>
                        <tr>
                          <th class="text-left">Name</th>
                          <th style="width:200px" class="text-left">Action</th>
                          <th></th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr v-for="item of backups" :key="item">
                          <td>{{ item }}</td>
                          <td>
                            <v-btn variant="text" icon="mdi-restore" title="Restore" size="small" @click="RestoreBackup(item)" />
                            <v-btn variant="text" icon="mdi-delete" title="Delete" size="small" @click="DeleteBackup(item)" />
                            <v-btn variant="text" icon="mdi-download" title="Download" size="small" @click="DownloadBackup(item)" />
                          </td>
                        </tr>
                      </tbody>
                    </template>
                  </v-table>
                </v-col>
              </v-row>
            </v-container>
        </v-card>
        
        <v-card class="pa-2 ma-2" variant="outlined" >
            <v-card-title>Export</v-card-title>
            <v-container>
                <v-btn color="primary" :href="urlPrefix + '/config'">Export</v-btn>
            </v-container>
        </v-card>
        
        <!-- <v-card class="pa-2 ma-2" variant="outlined" >
            <v-card-title>Firmware Update</v-card-title>
            <v-container>
                <v-file-input label="Firmware update" :disabled="true"></v-file-input>
                <v-btn color="primary" :disabled="true">Upload</v-btn>
            </v-container>
        </v-card> -->
      </v-col>
    </v-row>
</template>

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

export default {
  name: 'system',
  components: {
  },
  data () {
    return {
      ipChanged: false,
      ipConfValid: false,
      companionUpdateValid: false,
      companionVersion: '',
      backupName: '',
      ipConfig: { ip: '', netmask: 0, gateway: '', nameserver: '' },
      rules: {
        required: v => { return ((v && v.length && v.length > 0) || 'Required') },
        ip: v => {
          const re = /^$|^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
          return re.test(v) || 'Invalid IP'
        },
        nm: v => {
          const n = parseInt(v)
          return (v == (n + '') && n > 0 && n < 32) || 'Must be 1 to 31'
        },
        version: v => {
          const re = /^v?\d+\.\d+.\d+$/
          return re.test(v) || 'Invalid Version'
        }
      }
    }
  },
  computed: {
    nwIp: {
      get () { return this.ipChanged ? this.ipConfig.ip : this.$store.state.networkConfig.ip },
      set (value) { this.startEdit(); this.ipConfig.ip = value }
    },
    nwNm: {
      get () { return this.ipChanged ? this.ipConfig.netmask : this.$store.state.networkConfig.netmask },
      set (value) { this.startEdit(); this.ipConfig.netmask = value }
    },
    nwGw: {
      get () { return this.ipChanged ? this.ipConfig.gateway : this.$store.state.networkConfig.gateway },
      set (value) { this.startEdit(); this.ipConfig.gateway = value }
    },
    nwNs: {
      get () { return this.ipChanged ? this.ipConfig.nameserver : this.$store.state.networkConfig.nameserver },
      set (value) { this.startEdit(); this.ipConfig.nameserver = value }
    },
    remoteConnectionEnabled: {
      get () { return this.$store.state.remoteConnectionEnabled },
      set (_value) { }
    },
    nwChanged () { return this.ipChanged && JSON.stringify(this.ipConfig) !== JSON.stringify(this.$store.state.networkConfig) },
    boards () { return this.$store.state.boards },
    ports () { return this.$store.state.ports },
    backups () { return this.$store.state.backups },
    companionUpdateResult() { return this.$store.state.companionUpdateResult },
    remoteConnectionActive() { return this.$store.state.remoteConnectionActive },
    urlPrefix () { 
      if (window && window.location && window.location.hostname === 'localhost') {
        return 'http://10.198.9.111'
      }
      return ''
    }
  },
  mounted () {
  },
  methods: {
    startEdit () {
      if (!this.ipChanged) Object.assign(this.ipConfig, this.$store.state.networkConfig)
      this.ipChanged = true
    },
    getPortValue (port) {
      if (!port || !port.value) return 0
      return port.value
    },
    mousedown (portId) {
      if (portId) {
        this.$socket.emit('setTest', { id: portId, value: 1 })
      }
    },
    mouseup (portId) {
      if (portId) {
        this.$socket.emit('setTest', { id: portId, value: 0 })
      }
    },
    SetDateTimeToCurrent() {
      this.$socket.emit('setDateTime', new Date(Date.now()).toISOString())
    },
    SaveNwConfig() {
      if (this.nwChanged && this.$refs.ipConf.validate()) this.$socket.emit('setNetworkConfig', this.ipConfig)
    },
    UpdateCompanion() {
      if (this.$refs.companionUpdate.validate()) {
        this.$socket.emit('updateCompanion', this.companionVersion)
      }
    },
    SetRemoteConnection() {
      this.$socket.emit('setRemoteConnection', !this.remoteConnectionEnabled)
    },
    GetRemoteConnection() {
      this.$socket.emit('getRemoteConnection')
    },
    DoBackup() {
      this.$socket.emit('backup', this.backupName)
    },
    RestoreBackup(name) {
      this.$socket.emit('restore', name)
    },
    DeleteBackup(name) {
      this.$socket.emit('deleteBackup', name)
    },
    DownloadBackup(name) {
      window.location.assign(this.urlPrefix + '/backup/' + name)
    }
  }
}
</script>
