<template>
  <f7-app v-bind="f7params">
  <!-- Left panel with cover effect-->
  <f7-panel left cover>
    <f7-view>
      <f7-page>
        <f7-navbar title="ALVINN"></f7-navbar>
        <f7-list>
          <f7-list-item link="/settings/" view=".view-main" panel-close=".panel-left">Settings</f7-list-item>
          <f7-list-item link="/about/" view=".view-main"  panel-close=".panel-left">About ALVINN</f7-list-item>
          <f7-list-item link="/contact/" view=".view-main" panel-close=".panel-left">Contact</f7-list-item>
        </f7-list>
        <f7-toolbar class="panel-bar" position="bottom">
          <f7-link href="/specs/">version {{ alvinnVersion }}</f7-link>
        </f7-toolbar>
      </f7-page>
    </f7-view>
  </f7-panel>

  <!-- Your main view, should have "view-main" class -->
  <f7-view main class="safe-areas" url="/">
    <f7-popup :opened="showDisclaimer"
      style="height: auto; text-align: center;"
      :close-by-backdrop-click="false"
      :close-on-escape="false"
      :swipe-to-close="false"
    >
      <f7-block-title large>
        IMPORTANT
      </f7-block-title>
      <f7-block>
        <h3>
          ALVINN is for educational purposes only. It may not be used for medical diagnosis, intervention, or treatment.
        </h3>
        <div style="display: flex; justify-content: space-around; flex-direction: row; align-items: center;">
          <span v-if="!siteConf || !siteConf.agreeExpire == 0" style="height: min-content;">
            <f7-checkbox v-model:checked="rememberAgreement"/> Don't show again
          </span>
          <f7-button text="I agree" fill @click="setAgreement" />
        </div>
      </f7-block>
    </f7-popup>
  </f7-view>

  </f7-app>
</template>

<style>
  .panel-bar > .toolbar-inner {
    justify-content: center;
  }
</style>

<script>
  import { ref, onMounted } from 'vue'
  import { f7, f7ready } from 'framework7-vue'
  import { getDevice }  from 'framework7/lite-bundle'
  import cordovaApp from '../js/cordova-app.js'

  import YAML from 'yaml'

  import routes from '../js/routes.js'
  import store from '../js/store'

  export default {
    data () {
      return {
        rememberAgreement: false,
        siteAgreement: false,
        dateAgreement: null,
        showDisclaimer: false,
        alvinnVersion: store().getVersion,
        siteConf: {}
      }
    },
    async created () {
      if (!window.cordova) {
        const confText = await fetch('./conf/conf.yaml')
          .then((mod) => { return mod.text() })
        this.siteConf = YAML.parse(confText)
      }
      if (window.safari !== undefined) {store().safariDetected()}
      const loadSiteSettings = localStorage.getItem('siteSettings')
      if (loadSiteSettings) {
        let loadedSettings = JSON.parse(loadSiteSettings)
        this.siteAgreement = loadedSettings.siteAgreement
        this.rememberAgreement = loadedSettings.rememberAgreement
        this.dateAgreement = loadedSettings.dateAgreement && new Date(loadedSettings.dateAgreement)
      }
      const curDate = new Date ()
      const expireMonth = (this.dateAgreement?.getMonth() || 0) + (this.siteConf?.agreeExpire || 3)
      const agreeStillValid = this.dateAgreement && (curDate < this.dateAgreement.setMonth(expireMonth))
      if (this.siteAgreement && this.rememberAgreement && agreeStillValid && !this.siteConf?.agreeExpire == 0) {
        store().agree()
      } else {
        this.showDisclaimer = true        
      }
      store().set('enabledRegions',this.siteConf?.regions)
      store().set('siteDemo',this.siteConf?.demo)
      store().set('infoUrl',this.siteConf?.infoUrl)
      const loadServerSettings = localStorage.getItem('serverSettings')
      if (this.siteConf?.useExternal) {
        if (!['none','list','optional','required'].includes(this.siteConf.useExternal)) {
          console.warn(`'${this.siteConf.useExternal}' is not a valid value for useExternal configuration: using 'optional'`)
        } else {
          store().set('useExternal',this.siteConf.useExternal)
          if (this.siteConf.external) {
            store().set('externalServerList',this.siteConf.external)
          }
        }
      }
      if (this.siteConf.useExternal == 'none') {
        localStorage.setItem('serverSettings','{"use":false}')
      } else if (!loadServerSettings && !this.siteConf.external) {
        localStorage.setItem('serverSettings','{"use":false,"address":"10.188.0.98","port":"9001","previous":{"10.188.0.98":"9001"}}')
      } else if (this.siteConf.useExternal == 'required') {
        localStorage.setItem('serverSettings',`{"use":true,"address":"${this.siteConf.external[0].address}","port":${this.siteConf.external[0].port}}`)
      }
    },
    methods: {
      setAgreement () {
        this.siteAgreement = true
        store().agree()
        let newSettings = {
          siteAgreement: this.siteAgreement,
          rememberAgreement: this.rememberAgreement,
          dateAgreement: new Date()
        }
        let saveSiteSettings = new Promise(
          (saved,failed) => {
            try {
              localStorage.setItem('siteSettings',JSON.stringify(newSettings))
              saved()
            } catch {
              failed()
            }
          }
        )
        saveSiteSettings.then(
          () => {
            this.showDisclaimer = false
          },
          () => {
            const toast = f7.toast.create({
              text: 'ERROR: No settings saved',
              closeTimeout: 2000
            })
            toast.open()
          }
        )
      }
    },
    setup() {
      const device = getDevice();
      // Framework7 Parameters
      const loadThemeSettings = localStorage.getItem('themeSettings')
      let themeSettings = {}
      let darkTheme = 'auto'
      if (loadThemeSettings) { themeSettings = JSON.parse(loadThemeSettings) }
      if (themeSettings?.darkMode) darkTheme = themeSettings.darkMode
      const f7params = {
        name: 'ALVINN', // App name
        theme: 'auto', // Automatic theme detection
        darkMode: darkTheme,
        colors: {
          primary: '#0f206c',
        },

        // App routes
        routes: routes,

        // Register service worker (only on production build)
        serviceWorker: process.env.NODE_ENV ==='production' ? {
          path: './service-worker.js',
        } : {},

        // Input settings
        input: {
          scrollIntoViewOnFocus: device.cordova,
          scrollIntoViewCentered: device.cordova,
        },
        // Cordova Statusbar settings
        statusbar: {
          iosOverlaysWebView: true,
          androidOverlaysWebView: false,
        },
        // Navbar settings
        navbar: {
          mdCenterTitle: true,
          iosCenterTitle: true,
        },
        // Dialog settings
        dialog: {
          title: 'ALVINN'
        }
      };
      onMounted(() => {
        f7ready(() => {
          // Init cordova APIs (see cordova-app.js)
          if (device.cordova) {
            cordovaApp.init(f7);
          }

          // Call F7 APIs here
        });
      });

      return {
        f7params,
      }
    }
  }
</script>