import useJwt from 'auth/jwt/coreUseJwt';

/**
 * Return if user is logged in
 * This is completely up to you and how you want to store the token in your frontend application
 * e.g. If you are using cookies to store the application please update this function
 */
// eslint-disable-next-line arrow-body-style
export const hostname = 'localhost';
const hostPort = '8090';
export const hostPath = `http://${hostname}:${hostPort}`;
export const apiPath = window.location.href.match("localhost:3000") ? `${hostPath}/api` : (window.location.href.match(":3000") ? "http://" + window.location.hostname + ":8090/api" : `/api`);
export const paymentPath = window.location.href.match("localhost:3000") ? `${hostPath}/payment` : `/payment`;

export const delBugMode = true;

export const iAmSmartCallbackPath = () => {
  let hostname = window.location.hostname;
  if (hostname.match("pnspsuat")) {
    hostname = "pnspsuat.gld.gov.hk";
  }
  return hostname;
};

export const getNonce = () => {
  let hostname = window.location.hostname;
  if (hostname.match("localhost")) {
    hostname = "pnspsuat.gld.gov.hk";
  }
  return hostname;
};

export const getBowserType = () => {
  // console.log(navigator.userAgent)
  // const regex = /Mobi|Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Mi|huawei|Opera Mini|SAMSUNG|Samsung|SGH-[I|N|T]|GT-[I|N]|SM-[A|N|P|T|Z]|SHV-E|SCH-[I|J|R|S]|SPH-L/i;
  // if(!regex.test(navigator.userAgent)) 
  if (navigator.userAgent.indexOf("Edg") != -1) {
    if (navigator.userAgent.match(/Android/i)) return "Android_Edge"
    if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) return "iOS_Edge"
    return "PC_Browser"
  } else if (navigator.userAgent.indexOf("Chrome") != -1) {
    if (navigator.userAgent.match(/Android/i)) return "Android_Chrome"
    if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) return "iOS_Chrome"
    return "PC_Browser"
  } else if (navigator.userAgent.indexOf('CriOS') != -1) {
    if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) return "iOS_Chrome"
    return "PC_Browser"
  } else if (navigator.userAgent.indexOf("Safari") != -1 && navigator.userAgent.indexOf("Chrome") == -1) {
    if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) return "iOS_Safari"
    return "PC_Browser"
  } else if (navigator.userAgent.indexOf("Firefox") != -1) {
    if (navigator.userAgent.match(/Android/i)) return "Android_Firefox"
    if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) return "iOS_Firefox"
    return "PC_Browser"
  } else if (navigator.userAgent.match(/SAMSUNG|Samsung|SGH-[I|N|T]|GT-[I|N]|SM-[A|N|P|T|Z]|SHV-E|SCH-[I|J|R|S]|SPH-L/i)) {
    return "Android_Samsung"
  } else if (navigator.userAgent.match(/huawei/i)) {
    return "Android_Huawei"
  } else if (navigator.userAgent.match(/Mi/i)) {
    return "Android_Xiaomi"
  }
  return "PC_Browser";
}

export const isAppBowser = () => {
  return "PC_Browser" != getBowserType();
}


export const isUserLoggedIn = () => {
  return localStorage.getItem('userData') && localStorage.getItem(useJwt.jwtConfig.storageTokenKeyName);
};

export const getUserData = () => JSON.parse(localStorage.getItem('userData'));

export const isGranted = (auth) => {
  const abilities = getUserData() ? getUserData()["abilities"] : null;
  if (abilities == null || abilities.length == 0) return false;
  if (!Array.isArray(auth)) return _checkAuth(abilities, auth);

  if (auth.length > abilities.length) return false;
  let haveAuth = true;
  for (let i = 0; i < auth.length; i++) {
    haveAuth = _checkAuth(abilities, auth[i])
    if (!haveAuth) return haveAuth;
  }
  return haveAuth;
};

const _checkAuth = (abilities, auth) => {
  for (let i = 0; i < abilities.length; i++) {
    if (auth == abilities[i].actionSubjectCombo) return true;
  }
  return false;
}

export const isGrantedAny = (auth) => {
  const abilities = getUserData() ? getUserData()["abilities"] : null;
  if (abilities == null || abilities.length == 0) return false;
  if (!Array.isArray(auth)) return _checkAuth(abilities, auth);
  let haveAuth = false;
  for (let i = 0; i < auth.length; i++) {
    haveAuth = _checkAuth(abilities, auth[i])
    if (haveAuth) return haveAuth;
  }
  return haveAuth;
};

/**
 * This function is used for demo purpose route navigation
 * In real app you won't need this function because your app will navigate to same route for each users regardless of ability
 * Please note role field is just for showing purpose it's not used by anything in frontend
 * We are checking role just for ease
 * NOTE: If you have different pages to navigate based on user ability then this function can be useful. However, you need to update it.
 * @param {String} userRole Role of user
 */
export const getHomeRouteForLoggedInUser = (userRole) => {
  if (userRole === 'admin') return '/';
  if (userRole === 'user') return '/';
  if (userRole === 'client') return { name: 'access-control' };
  return { name: 'auth-login' };
};

// open payment record
export const local = { en: "en-us", zh: "zh-hk", cn: "zh-cn" };
export const preferpaymentmethods = ['visa', 'mastercard', 'pps', 'creditcard', 'fps'];

export const getPaymentMethod = (paymentMethod) => {
  if (paymentMethod == "online") return 'payOnlineMethod';
  if (paymentMethod == "demandNote") return 'payDnMethod';
  if (paymentMethod == "office") return 'payNPGOMethod';
  return "other";
}

export const getPaymentMethodGLD = (paymentMethod) => {
  if (paymentMethod == "online") return 'Online';
  if (paymentMethod == "demandNote") return 'Demand Note';
  if (paymentMethod == "office") return 'NPGO Collection Office';
  return "other";
}

export const getSearchCriteria = (path) =>{
  let searchCriteria = ""
  if (localStorage.getItem('searchCriteria')==""){
    return searchCriteria
  } else if (Object.keys(localStorage.getItem('searchCriteria')).length>0){
    searchCriteria = JSON.parse(localStorage.getItem("searchCriteria"))
    if (searchCriteria.path === path){
      return searchCriteria.data
    } else {
      return ""
    }
  }
}

export const checkSearchCriteriaPath = (path) =>{
  if(!path.startsWith("/application")
      || path === "/application/search"){
          if(!path.startsWith("/user/")){
            if(!path.startsWith("/publicNotice/")|| path === "/publicNotice"){
                return true
            }
          }
  }
}

export const getPaymentMethodByCode = (code) => {
  if (code === "01,PPSB,PPS") return "PPS";
  if (code === "02,BCMP,CreditCard" || code === "03,BCMP,CreditCard") return "Credit Card";
  if (code === "04,BCFP,FPS") return "FPS";
  return "other";
};

export function setPageTitle(title) {
  document.title = `${title} - PNSPS | Government Logistics Department`;
}