<template>
  <f7-page name="settings">
    <!-- Top Navbar -->
    <f7-navbar :sliding="false">
      <f7-nav-left>
        <f7-link class="link icon-only ripple-inset" @click="confirmBack">
          <f7-icon class="icon-back"></f7-icon>
        </f7-link>
      </f7-nav-left>
      <f7-nav-title sliding>Settings</f7-nav-title>
    </f7-navbar>
    <f7-block style="display: flex; flex-direction: column; align-items: center;">
      <div style="display: flex; flex-direction: column; align-items: center;">
        <f7-block-title medium>Dark Mode</f7-block-title>
        <f7-list style="width: 100%;">
          <f7-list-item title="Auto" :checked="themeSettings.darkMode == 'auto'" radio name="darkmode" radio-icon="end" @change="setDarkMode('auto')" ></f7-list-item>
          <f7-list-item title="Light" :checked="themeSettings.darkMode.toString() == 'false'" radio name="darkmode" radio-icon="end" @change="setDarkMode(false)" ></f7-list-item>
          <f7-list-item title="Dark" :checked="themeSettings.darkMode.toString() == 'true'" radio name="darkmode" radio-icon="end" @change="setDarkMode(true)" ></f7-list-item>
        </f7-list>
        <f7-block-title @click="toggleSettingsView" medium><f7-icon :f7="showAdvanced ? 'chevron_down' : 'chevron_right'" /> Advanced Settings </f7-block-title>
        <div ref="advancedSettings" class="settings-container">
          <div style="display:flex; justify-content:space-between; width: 100%; margin-bottom: 10px;">
            <span style="margin-left: 16px;">Use mini ALVINN<f7-icon size="16" style="padding-left: 5px;" f7="question_diamond_fill" tooltip="faster, less accurate: recommended for slower devices" /></span>
            <f7-toggle v-model:checked="otherSettings.mini" style="margin-right: 16px;" @change="setDirty()" />
          </div>
          <div style="display:flex; justify-content:space-between; width: 100%; margin-bottom: 10px;">
            <span style="margin-left: 16px;">Enable demo mode</span>
            <f7-toggle v-model:checked="otherSettings.demo" style="margin-right: 16px;" @change="setDirty()" />
          </div>
          <div style="display:flex; justify-content:space-between; width: 100%; margin-bottom: 10px;">
            <span style="margin-left: 16px;">Disable video estimates<f7-icon size="16" style="padding-left: 5px;" f7="question_diamond_fill" tooltip="faster: recommended for slower devices" /></span>
            <f7-toggle v-model:checked="otherSettings.disableVideo" style="margin-right: 16px;" />
          </div>
          <div  v-if="serverToggle">
            <div style="display:flex; justify-content:space-between; width: 100%">
              <span style="margin-left: 16px;">Use external server</span>
              <f7-toggle v-model:checked="serverSettings.use" style="margin-right: 16px;" @change="setDirty()" />
            </div>
            <f7-list >
              <f7-list-input :disabled="!serverSettings.use || serverList" v-model:value="serverSettings.address" label="Server address" type="text" placeholder="127.0.0.1" />
              <f7-list-input :disabled="!serverSettings.use || serverList" v-model:value="serverSettings.port" label="Server port" type="text" placeholder="9001" />
            </f7-list>
            <span>Other servers</span>
            <f7-list :dividers="true" :outline="true" :strong="true" :inset="true" style="width: calc(100% - 32px); margin-top: 0;">
              <f7-list-item v-for="(addObj) in externalIp" :disabled="!serverSettings.use" :title="addObj.name" @click="setServerProps(addObj.address, addObj.port)"></f7-list-item>
              <f7-list-item v-if="!serverList" v-for="(port, add) in otherIp" :disabled="!serverSettings.use" :title="add" @click="setServerProps(add, port)">{{ port }}</f7-list-item>
              <f7-list-item v-if="Object.keys(otherIp).length == 0 && externalIp.length == 0" title="No previous server settings"></f7-list-item>
            </f7-list>
          </div>
        </div>
        <f7-button fill @click="saveAllSettings">SAVE</f7-button>
      </div>
    </f7-block>
  </f7-page>
</template>

<style>
  .settings-container {
    max-height: 0px;
    overflow: hidden;
    transition: max-height 0.2s ease-out;
  }
</style>

<script>
  import { f7 } from 'framework7-vue'
  import store from '../js/store'

  export default {
    data () {
      return {
        showAdvanced: false,
        isDirty: false,
        otherSettings: {
          mini: false
        },
        serverSettings: {
          use: false,
          address: '127.0.0.1',
          port: '9000',
          previous: {}
        },
        themeSettings: {
          darkMode: 'auto'
        }
      }
    },
    setup() {
      return store()
    },
    computed: {
      otherIp () {
        let filteredIps = {}
        for (var oldIp in this.serverSettings.previous) {
          if (oldIp != this.serverSettings.address) {
            filteredIps[oldIp] = this.serverSettings.previous[oldIp]
          }
        }
        return filteredIps
      },
      serverToggle () {
        return ['optional','list'].includes(this.externalType)
      },
      serverList () {
        return this.externalType == 'list'
      },
      externalIp () {
        return this.getServerList()
      }
    },
    created () {
        var loadServerSettings = localStorage.getItem('serverSettings')
        if (loadServerSettings) this.serverSettings =  JSON.parse(loadServerSettings)
        if (!this.serverSettings.previous) this.serverSettings.previous = {}
        var loadThemeSettings = localStorage.getItem('themeSettings')
        if (loadThemeSettings) this.themeSettings = JSON.parse(loadThemeSettings)
        var loadOtherSettings = localStorage.getItem('otherSettings')
        if (loadOtherSettings) this.otherSettings = JSON.parse(loadOtherSettings)
    },
    methods: {
      saveAllSettings () {
        let saveSetting = new Promise(
          (saved,failed) => {
            try {
              if (this.serverSettings.use && !this.externalIp.some( (srv) => srv.address == this.serverSettings.address)) {
                this.serverSettings.previous[this.serverSettings.address] = this.serverSettings.port
              }
              localStorage.setItem('serverSettings',JSON.stringify(this.serverSettings))
              localStorage.setItem('themeSettings',JSON.stringify(this.themeSettings))
              localStorage.setItem('otherSettings',JSON.stringify(this.otherSettings))
              saved()
            } catch {
              failed()
            }
          }
        )
        saveSetting.then(
          () => {
            var toast = f7.toast.create({
              text: 'Settings saved',
              closeTimeout: 2000
            })
            toast.open()
            this.isDirty = false;
          },
          () => {
            var toast = f7.toast.create({
              text: 'ERROR: No settings saved',
              closeTimeout: 2000
            })
            toast.open()
          }
        )
      },
      setDirty () {
        this.isDirty = true
      },
      setDarkMode (mode) {
        this.themeSettings.darkMode = mode
        f7.setDarkMode(mode)
        this.isDirty = true
      },
      setServerProps (add, port) {
        this.serverSettings.address = add
        this.serverSettings.port = port
        this.isDirty = true
      },
      toggleSettingsView () {
        this.showAdvanced = !this.showAdvanced
        //this.$refs.advancedSettings.style.maxHeight = `${this.showAdvanced ? this.$refs.advancedSettings.scrollHeight : 0}px`
        this.$refs.advancedSettings.style.maxHeight = this.showAdvanced ? '100%' : '0px'
      },
      confirmBack () {
        if (this.isDirty) {
          f7.dialog.confirm('If you leave this page you will loose unsaved changes to your settings.', () => {
            f7.views.main.router.back()
          })
        } else {
          f7.views.main.router.back()
        }
      }
    }
  }
</script>