<template>
  <v-row align="center" justify="center" class="mx-auto mt-sm-12 mb-8">
    <v-col cols="12" offset-md="4">
      <form>
        <v-row>
          <v-col cols="12" class="hidden-md-and-up">
            <v-img
              :src="require('../assets/logo.svg')"
              contain
              height="64"
            ></v-img>
          </v-col>
          <v-col cols="12" md="7" class="hidden-sm-and-down">
            <v-img
              :src="require('../assets/logo.svg')"
              contain
              height="128"
            ></v-img>
          </v-col>
          <v-col cols="12" md="7" v-if="formState.errorBoxMessage">
            <gz-error :errorBoxMessage="formState.errorBoxMessage"></gz-error>
          </v-col>

          <v-col cols="12" md="7" v-if="showEvalUsers == true">
            <v-select
              v-model="selectedTrialUserId"
              :items="selectLists.trialUsers"
              item-text="name"
              item-value="l"
              label="Trial mode example users"
              prepend-icon="fa-question-circle"
              @click:prepend="trialHelpClick"
              @input="trialUserSelected"
              return-object
              :data-cy="!!$ay.dev ? 'selecttrialuser' : false"
            >
            </v-select>
          </v-col>
          <v-col cols="12" md="7">
            <v-text-field
              name="username"
              id="username"
              v-model="input.username"
              prepend-icon="fa-user"
              autofocus
              autocomplete="off"
              autocorrect="off"
              autocapitalize="off"
              spellcheck="false"
              :error="errorBadCreds"
              v-focus
              v-on:keyup.enter="onEnterUserName"
            ></v-text-field>
          </v-col>
          <v-col cols="12" md="7">
            <v-text-field
              name="password"
              id="password"
              v-model="input.password"
              :append-outer-icon="reveal ? 'fa-eye' : 'fa-eye-slash'"
              prepend-icon="fa-key"
              :type="reveal ? 'text' : 'password'"
              :error="errorBadCreds"
              v-on:keyup.enter="login"
              @click:append-outer="reveal = !reveal"
            ></v-text-field>
          </v-col>
          <v-col cols="12" md="7" mt-1>
            <v-btn color="primary" v-on:click="login()" value="LOGIN">
              <v-icon>fa-sign-in-alt</v-icon>
            </v-btn>
          </v-col>

          <template v-if="$ay.dev">
            <v-col cols="12">
              <span class="subtitle-2 secondary--text">DEVELOPMENT MODE</span>
            </v-col>
          </template>
        </v-row>
      </form>
    </v-col>
  </v-row>
</template>

<script>
/*  xeslint-disable */
import auth from "../api/auth";

export default {
  data() {
    return {
      input: {
        username: "superuser",
        password: "l3tm3in"
      },

      errorBadCreds: false,
      reveal: false,
      formState: { errorBoxMessage: null },
      showEvalUsers: false,
      selectedTrialUserId: 1,
      selectLists: {
        trialUsers: [
          {
            name: "AyaNova administrator - all",
            l: "superuser",
            p: "l3tm3in"
          },
          {
            name: "Accounting",
            l: "Accounting",
            p: "Accounting"
          },
          {
            name: "Business admin",
            l: "BizAdminFull",
            p: "BizAdminFull"
          },
          {
            name: "Business admin - limited",
            l: "BizAdminLimited",
            p: "BizAdminLimited"
          },
          {
            name: "Customer",
            l: "CustomerFull",
            p: "CustomerFull"
          },
          {
            name: "Customer - limited",
            l: "CustomerLimited",
            p: "CustomerLimited"
          },
          {
            name: "Dispatcher",
            l: "DispatchFull",
            p: "DispatchFull"
          },
          {
            name: "Dispatcher - limited",
            l: "DispatchLimited",
            p: "DispatchLimited"
          },
          {
            name: "Head office",
            l: "HeadOffice",
            p: "HeadOffice"
          },
          {
            name: "Inventory",
            l: "InventoryFull",
            p: "InventoryFull"
          },
          {
            name: "Inventory - limited",
            l: "InventoryLimited",
            p: "InventoryLimited"
          },
          {
            name: "Operations",
            l: "OpsAdminFull",
            p: "OpsAdminFull"
          },
          {
            name: "Operations - limited",
            l: "OpsAdminLimited",
            p: "OpsAdminLimited"
          },
          {
            name: "Sales",
            l: "SalesFull",
            p: "SalesFull"
          },
          {
            name: "Sales - limited",
            l: "SalesLimited",
            p: "SalesLimited"
          },
          {
            name: "Subcontractor",
            l: "SubContractorFull",
            p: "SubContractorFull"
          },
          {
            name: "Subcontractor - limited",
            l: "SubContractorLimited",
            p: "SubContractorLimited"
          },
          {
            name: "Technician",
            l: "TechFull",
            p: "TechFull"
          },
          {
            name: "Technician - limited",
            l: "TechLimited",
            p: "TechLimited"
          },
          {
            name: "Translation - Deutsch / German",
            l: "de",
            p: "de"
          },
          {
            name: "Translation - Español / Spanish",
            l: "es",
            p: "es"
          },
          {
            name: "Translation - Français / French",
            l: "fr",
            p: "fr"
          }
        ]
      }
    };
  },
  created() {
    let vm = this;

    // (async function() {
    //   await window.$gz.dialog.displayLTModalNotificationMessage(
    //     "MaintenanceExpiredNote",
    //     "MaintenanceExpired",
    //     "error",
    //     "https://www.ayanova.com/subscriptionexpired.htm"
    //   );
    // })();

    window.$gz.eventBus.$emit("menu-change", {
      isMain: true,
      icon: "",
      title: ""
    });
    window.$gz.api
      .get("notify/hello")
      .then(res => {
        if (res.data != null) {
          vm.showEvalUsers = res.data;
        }
      })
      .catch(function handleGetTrialModeError(error) {
        //squash it, this isn't critical
      });
  },

  methods: {
    trialUserSelected(item) {
      this.input.password = item.p;
      this.input.username = item.l;
    },
    trialHelpClick: function() {
      //open help nav for trial login
      window.$gz.eventBus.$emit("menu-click", {
        key: "app:help",
        data: "ay-start-trial-login"
      });
    },
    onEnterUserName: function() {
      //move focus to password
      document.getElementsByName("password")[0].focus();
    },
    login() {
      let vm = this;
      if (vm.input.username != "" && vm.input.password != "") {
        vm.errorBadCreds = false;
        auth
          .authenticate(vm.input.username, vm.input.password)
          .then(() => {
            //check if support and updates has expired and show warning if so
            if (vm.$store.state.globalSettings.maintenanceExpired) {
              (async function() {
                await window.$gz.dialog.displayLTModalNotificationMessage(
                  "MaintenanceExpiredNote",
                  "MaintenanceExpired",
                  "error",
                  "https://www.ayanova.com/subscriptionexpired.htm"
                );
              })();
            }
            if (vm.$store.state.openObject != null) {
              window.$gz.eventBus.$emit("openobject", null);
            } else {
              vm.$router.push(vm.$store.state.homePage);
            }
          })
          .catch(function handleCaughtLoginError(error) {
            //bad creds?
            if (
              error.message &&
              error.message.includes("ErrorUserNotAuthenticated")
            ) {
              vm.errorBadCreds = true;
              return;
            }
            //server closed by server state setting?
            if (error.code == 2000 || error.code == 2001) {
              vm.formState.errorBoxMessage = error.message;
              return;
            }
            //probably here because server unresponsive.
            if (error.message) {
              let msg = error.message;
              if (
                msg.includes("NetworkError") ||
                msg.includes("Failed to fetch")
              ) {
                msg =
                  "Could not connect to AyaNova server at " +
                  window.$gz.api.APIUrl("") +
                  "\r\nError: " +
                  error.message;
              }
              vm.formState.errorBoxMessage = msg;
              return;
            }
            /* xeslint-disable-next-line */

            /* 
            server down errors:
            firefox: NetworkError when attempting to fetch resource."
            brave: Error in login.vue catch: TypeError: Failed to fetch
            chrome: Error in auth.js catch: TypeError: Failed to fetch
            */

            //-----
          });
      }
    }
  },
  beforeRouteEnter(to, from, next) {
    //very important as this in conjunction with the menu options means
    //navigation guards work properly by just sending people here
    next(() => {
      auth.logout();
      next();
    });
  }
};
</script>
