function addNavItem(title, icon, route, navItems, key, testid, color = null) {
  if (!testid) {
    testid = route;
  }

  const o = {
    title,
    icon,
    route,
    navItems,
    key: key,
    testid: testid
  };
  if (color != null) {
    o["color"] = color;
  }
  o.navItems.forEach(z => {
    if (z.testid == null) {
      z.testid = z.route;
    }
  });

  window.$gz.store.commit("addNavItem", o);
}

function initNavPanel() {
  let key = 0;
  let sub = [];

  /*Service = 1,
NotService = 2,
Customer = 3,
HeadOffice = 4,        
ServiceContractor = 5 */

  //########## OUTSIDE USERS GROUP (CUSTOMER / HEADOFFICE) ###
  if (window.$gz.store.getters.isCustomerUser == true) {
    //clear sublevel array
    sub = [];

    //Set homePage in store to customer csr for this user type
    let CustomerHomePageSet = false;

    //USER SETTINGS
    //if (window.$gz.store.state.customerRights.userSettings == true) {
    sub.push({
      title: "UserSettings",
      icon: "$sockiUserCog",
      route: "/home-user-settings",
      key: key++
    });

    window.$gz.store.commit("setHomePage", "/home-user-settings");
    CustomerHomePageSet = true;
    //  }

    if (window.$gz.store.getters.canSubscribeToNotifications) {
      sub.push({
        title: "NotifySubscriptionList",
        icon: "$sockiBullhorn",
        route: "/home-notify-subscriptions",
        key: key++
      });

      window.$gz.store.commit("setHomePage", "/home-notify-subscriptions");
      CustomerHomePageSet = true;
    }

    //** CUSTOMER LOGIN HOME (TOP)
    addNavItem("Home", "$sockiHome", undefined, sub, key++, "homecustomer");

    //last resort home page if nothing else kicked in
    if (!CustomerHomePageSet) {
      window.$gz.store.commit("setHomePage", "/no-features-available");
    }

    return;
  }

  //###### ALL INSIDE USERS FROM HERE DOWN ###############

  //####### HOME GROUP

  //DASHBOARD

  sub.push({
    title: "Dashboard",
    icon: "$sockiTachometer",
    route: "/home-dashboard",
    key: key++
  });

  //SEARCH
  sub.push({
    title: "Search",
    icon: "$sockiSearch",
    route: "/home-search",
    key: key++
  });

  //SCHEDULE (personal)
  sub.push({
    title: "Schedule",
    icon: "$sockiCalendarDay",
    route: "/home-schedule",
    key: key++
  });

  //MEMOS
  sub.push({
    title: "MemoList",
    icon: "$sockiInbox",
    route: "/home-memos",
    key: key++
  });

  //REMINDERS
  sub.push({
    title: "ReminderList",
    icon: "$sockiStickyNote",
    route: "/home-reminders",
    key: key++
  });

  //REVIEWS
  sub.push({
    title: "ReviewList",
    icon: "$sockiCalendarCheck",
    route: "/home-reviews",
    key: key++
  });

  //USER SETTINGS
  sub.push({
    title: "UserSettings",
    icon: "$sockiUserCog",
    route: "/home-user-settings",
    key: key++
  });

  //USER NOTIFICATION SUBSCRIPTIONS
  sub.push({
    title: "NotifySubscriptionList",
    icon: "$sockiBullhorn",
    route: "/home-notify-subscriptions",
    key: key++
  });

  //HISTORY / MRU / ACTIVITY (personal)
  sub.push({
    title: "History",
    icon: "$sockiHistory",
    route: `/history/3/${window.$gz.store.state.userId}/true`,
    key: key++,
    testid: "/home-history"
  });

  //HOME
  if (sub.length > 0) {
    //Set homePage in store to dashboard
    window.$gz.store.commit("setHomePage", "/home-dashboard");
    addNavItem("Home", "$sockiHome", undefined, sub, key++, "home");
  }

  ////////////////////////////////////////////////////////
  // BUSINESS GROUP
  //

  sub = [];

  sub.push({
    title: "GZCaseList",
    icon: "$sockiCoffee",
    route: "/biz-gzcase-list",
    key: key++
  });

  sub.push({
    title: "LicenseList",
    icon: "$sockiGem",
    route: "/biz-license-list",
    key: key++
  });

  sub.push({
    title: "TrialLicenseRequestList",
    icon: "$sockiHandHoldingWater",
    route: "/biz-trial-request-list",
    key: key++
  });

  sub.push({
    title: "SubscriptionServerList",
    icon: "$sockiCloud",
    route: "/biz-subscription-server-list",
    key: key++
  });

  sub.push({
    title: "PurchaseList",
    icon: "$sockiShoppingCart",
    route: "/biz-purchase-list",
    key: key++
  });

  sub.push({
    title: "VendorNotificationList",
    icon: "$sockiCommentDollar",
    route: "/biz-vendor-notification-list",
    key: key++
  });

  sub.push({
    title: "ProductList",
    icon: "$sockiBarCode",
    route: "/biz-product-list",
    key: key++
  });

  sub.push({
    title: "VendorList",
    icon: "$sockiStore",
    route: "/biz-vendor-list",
    key: key++
  });

  if (window.$gz.role.canOpen(window.$gz.type.Customer)) {
    addNavItem(
      "BusinessSettings",
      "$sockiBriefcase",
      undefined,
      sub,
      key++,
      "biz"
    );
  }
  ////////////////////////////////////////////////////

  //######### CUSTOMER GROUP
  if (window.$gz.role.canOpen(window.$gz.type.Customer)) {
    //these all require Customer rights so all in the same block

    //clear sublevel array
    sub = [];

    //CUSTOMERS subitem
    sub.push({
      title: "CustomerList",
      icon: "$sockiAddressCard",
      route: "/cust-customers",
      key: key++
    });

    //HEAD OFFICES subitem
    sub.push({
      title: "HeadOfficeList",
      icon: "$sockiSitemap",
      route: "/cust-head-offices",
      key: key++
    });

    //Customer / Headoffice Users subitem
    sub.push({
      title: "Contacts",
      icon: "$sockiUsers",
      route: "/cust-users",
      key: key++
    });

    sub.push({
      title: "CustomerNotifySubscriptionList",
      icon: "$sockiBullhorn",
      route: "/cust-notify-subscriptions",
      key: key++
    });

    // ** CUSTOMER (TOP)
    addNavItem(
      "CustomerList",
      "$sockiAddressBook",
      undefined,
      sub,
      key++,
      "customer"
    );
  }

  // //#######  SERVICE GROUP

  // sub = [];

  // //SCHEDULE (shared)

  // sub.push({
  //   title: "Schedule",
  //   icon: "$sockiCalendarAlt",
  //   route: "/svc-schedule",
  //   key: key++
  // });

  // //**** SHARED (TOP GROUP)
  // if (
  //   sub.length > 0 &&
  //   !window.$gz.role.hasRole([
  //     window.$gz.role.AUTHORIZATION_ROLES.TechRestricted
  //   ])
  // ) {
  //   addNavItem("Service", "$sockiToolbox", undefined, sub, key++, "service");
  // }

  //******************  ACCOUNTING

  //SOCKEYE Keeping this for very likely future accounting functionality
  sub = [];

  // ** ACCOUNTING (TOP)
  if (sub.length > 0) {
    addNavItem(
      "Accounting",
      "$sockiCoins",
      undefined,
      sub,
      key++,
      "accounting"
    );
  }

  //#############  ADMINISTRATION

  //clear sublevel array
  sub = [];

  // GLOBAL SETTINGS
  if (window.$gz.role.canOpen(window.$gz.type.Global)) {
    sub.push({
      title: "AdministrationGlobalSettings",
      icon: "$sockiCogs",
      route: "/adm-global-settings",
      key: key++
    });
  }

  // USERS
  if (window.$gz.role.canOpen(window.$gz.type.User)) {
    sub.push({
      title: "UserList",
      icon: "$sockiUsers",
      route: "/adm-users",
      key: key++
    });
  }

  //TRANSLATION
  if (window.$gz.role.canOpen(window.$gz.type.Translation)) {
    sub.push({
      title: "TranslationList",
      icon: "$sockiLanguage",
      route: "/adm-translations",
      key: key++
    });
  }

  //REPORT TEMPLATES
  if (window.$gz.role.canChange(window.$gz.type.Report)) {
    sub.push({
      title: "ReportList",
      icon: "$sockiThList",
      route: "/adm-report-templates",
      key: key++
    });
  }

  //FILES IN DATABASE
  if (window.$gz.role.canOpen(window.$gz.type.FileAttachment)) {
    sub.push({
      title: "Attachments",
      icon: "$sockiPaperclip",
      route: "/adm-attachments",
      key: key++
    });
  }

  //EVENT LOG / HISTORY
  if (window.$gz.role.canOpen(window.$gz.type.Global)) {
    //not really an appropriate object here just guessing
    sub.push({
      title: "History",
      icon: "$sockiHistory",
      route: "/adm-history",
      key: key++
    });
  }

  //IMPORT
  if (window.$gz.role.canOpen(window.$gz.type.Global)) {
    //again, not really an appropriate object type
    sub.push({
      title: "Import",
      icon: "$sockiFileImport",
      route: "/adm-import",
      key: key++
    });
  }

  //INTEGRATION
  //decision here is that only teh biz admin can *control* or remove an integration
  //even though all full role inside users can create or edit integrations (just not through the Sockeye user interface)
  //this is required to support integrations made for various roles like inventory accounting etc
  if (window.$gz.role.canOpen(window.$gz.type.Global)) {
    sub.push({
      title: "IntegrationList",
      icon: "$sockiCampground",
      route: "/adm-integrations",
      key: key++
    });
  }

  // ** ADMINISTRATION (TOP)
  if (sub.length > 0) {
    addNavItem(
      "Administration",
      "$sockiUserTie",
      undefined,
      sub,
      key++,
      "administration"
    );
  }

  //############ OPERATIONS

  //clear sublevel array
  sub = [];

  // BACKUP
  if (window.$gz.role.canOpen(window.$gz.type.Backup)) {
    sub.push({
      title: "Backup",
      icon: "$sockiFileArchive",
      route: "/ops-backup",
      key: key++
    });
  }

  // SERVER STATE
  if (window.$gz.role.canChange(window.$gz.type.ServerState)) {
    sub.push({
      title: "ServerState",
      icon: "$sockiDoorOpen",
      route: "/ops-server-state",
      key: key++
    });
  }

  // JOBS
  if (window.$gz.role.canOpen(window.$gz.type.ServerJob)) {
    sub.push({
      title: "ServerJobs",
      icon: "$sockiRobot",
      route: "/ops-jobs",
      key: key++
    });
  }

  // LOGS
  if (window.$gz.role.canOpen(window.$gz.type.LogFile)) {
    sub.push({
      title: "ServerLog",
      icon: "$sockiHistory",
      route: "/ops-log",
      key: key++
    });
  }

  //METRICS
  if (window.$gz.role.canOpen(window.$gz.type.ServerMetrics)) {
    sub.push({
      title: "ServerMetrics",
      icon: "$sockiFileMedicalAlt",
      route: "/ops-metrics",
      key: key++
    });

    // //PROFILE
    // //metrics rights
    // sub.push({
    //   title: "ServerProfiler",
    //   icon: "$sockiBinoculars",
    //   route: "/ops-profile",
    //   key: key++
    // });
  }

  //NOTIFICATION CONFIG AND HISTORY
  if (window.$gz.role.canOpen(window.$gz.type.OpsNotificationSettings)) {
    sub.push({
      title: "OpsNotificationSettings",
      icon: "$sockiBullhorn",
      route: "/ops-notification-settings",
      key: key++
    });
  }

  if (window.$gz.role.canOpen(window.$gz.type.OpsNotificationSettings)) {
    sub.push({
      title: "NotificationDeliveryLog",
      icon: "$sockiHistory",
      route: "/ops-notify-log",
      key: key++
    });
  }

  if (window.$gz.role.canOpen(window.$gz.type.OpsNotificationSettings)) {
    sub.push({
      title: "NotificationCustomerDeliveryLog",
      icon: "$sockiHistory",
      route: "/ops-customer-notify-log",
      key: key++
    });
  }

  // OPS VIEW SERVER CONFIGURATION
  if (window.$gz.role.canOpen(window.$gz.type.GlobalOps)) {
    sub.push({
      title: "ViewServerConfiguration",
      icon: "$sockiInfoCircle",
      route: "/ops-view-configuration",
      key: key++
    });
  }

  // ** OPERATIONS (TOP)
  if (sub.length > 0) {
    addNavItem(
      "Operations",
      "$sockiServer",
      undefined,
      sub,
      key++,
      "operations"
    );
  }
}

async function getUserOptions() {
  try {
    const res = await window.$gz.api.get(
      "user-option/" + window.$gz.store.state.userId
    );

    if (res.error) {
      //In a form this would trigger a bunch of validation or error display code but for here and now:
      //convert error to human readable string for display and popup a notification to user
      const msg = window.$gz.api.apiErrorToHumanString(res.error);
      window.$gz.store.commit(
        "logItem",
        "Initialize::() fetch useroptions -> error" + msg
      );
      window.$gz.eventBus.$emit("notify-error", msg);
    } else {
      //Check if overrides and use them here
      //or else use browser defaults

      const l = {
        languageOverride: null,
        timeZoneOverride: null,
        currencyName: null,
        hour12: true,
        //uiColor: "#000000ff",
        emailAddress: null,
        mapUrlTemplate: null
      };

      l.languageOverride = res.data.languageOverride;
      l.timeZoneOverride = res.data.timeZoneOverride;

      //No browser setting for this so meh
      l.currencyName = res.data.currencyName;

      if (res.data.hour12 != null) {
        l.hour12 = res.data.hour12;
      }

      //  l.uiColor = res.data.uiColor || "#000000ff";
      l.emailAddress = res.data.emailAddress || null;

      l.mapUrlTemplate = res.data.mapUrlTemplate || null;

      window.$gz.store.commit("setUserOptions", l);
    }
  } catch (error) {
    window.$gz.store.commit(
      "logItem",
      "Initialize::() fetch useroptions -> error" + error
    );
    throw new Error(window.$gz.errorHandler.errorToString(error));
  }
}

/////////////////////////////////////
// Initialize the app
// on change of authentication status
export default function initialize() {
  // eslint-disable-next-line no-async-promise-executor
  return new Promise(async function(resolve, reject) {
    if (!window.$gz.store.state.authenticated) {
      throw new Error("initialize: Error, called but user not authenticated!");
    }
    try {
      await window.$gz.translation.cacheTranslations(
        window.$gz.translation.coreKeys
      );
      initNavPanel();
      await getUserOptions();

      resolve();
    } catch (err) {
      reject(err);
    }
  });
}
