import _ from "lodash";
import React from "react";
import { Platform, StatusBar, Dimensions } from "react-native";
import { Text } from "./components";
import Constants from "expo-constants";
import Config from "./config";
import { LINEGREY } from "./colours";
import { getSessionTokenAWS } from "./session";

// seperated files to export
import detectFaces from "./js/images/detectFaces";
import findLandmarkRange from "./js/images/findLandmarkRange";
import getScaledOffset from "./js/images/getScaledOffset";
import getSiteLevelFromState from "./js/site/getSiteLevelFromState";
import isTVEnabled from "./js/site/isTVEnabled";
const TIMESTAMP_FORMAT = "D MMM • h:mma";
const DATE_FORMAT = "D MMM YYYY";
const getUrl = (baseAction, action, query) => {
  const {
    baseAPIUrl,
    baseStage
  } = Config.env;
  let queryPart = "";
  if (query) {
    _.keys(query).forEach((key, index) => {
      queryPart += `${index === 0 ? "?" : "&"}${key}=${encodeURIComponent(query[key])}`;
    });
  }
  return `${baseAPIUrl}/${baseAction}-${baseStage}/${action}${queryPart}`;
};
const getAuthTokenHeader = () => {
  return new Promise((resolve, reject) => {
    getSessionTokenAWS().then(idToken => {
      resolve(`Bearer ${idToken}`);
    });
  });
};
const getShadowStyle = () => {
  if (Platform.OS === "ios") {
    return {
      shadowColor: "#000",
      shadowOffset: {
        width: 0,
        height: 1
      },
      shadowOpacity: 0.1,
      shadowRadius: 3,
      backgroundColor: "#fff"
    };
  }
  return {
    borderColor: LINEGREY,
    backgroundColor: "#fff",
    elevation: 8
  };
};
const StatusBarHeight = size => {
  return getStatusBarHeight() + size;
};
const getStatusBarHeight = () => {
  return Platform.OS === "ios" ? Constants.statusBarHeight : StatusBar.currentHeight;
};
const getSiteSettingFromState = (state, key, defaultValue) => {
  if (state && state.user && state.user.siteSettings && !_.isUndefined(state.user.siteSettings[key])) {
    return state.user.siteSettings[key];
  }
  return defaultValue || null;
};
const getValueOrDefault = (value, def) => {
  return !_.isUndefined(value) ? value : def;
};
const getExtension = url => {
  if (!url) {
    return null;
  }
  const fileSplit = url.split(".");
  return fileSplit[fileSplit.length - 1].toLowerCase();
};
const getFileName = (url, noExtension) => {
  if (!url) {
    return null;
  }
  const fileSplit = url.split("/");
  const name = fileSplit[fileSplit.length - 1].toLowerCase();
  if (!noExtension) {
    return name;
  }
  return name.split(".")[0];
};
const isVideo = url => {
  const extension = getExtension(url);
  return ["mov", "mp4"].includes(extension);
};
const isVideoUrl = url => {
  const urlToCheck = getValidUrl(url);
  if (isVideo(urlToCheck)) {
    return true;
  }
  if (isYoutube(urlToCheck)) {
    return true;
  }
  if (isVimeo(urlToCheck)) {
    return true;
  }
  return false;
};
const isStockImage = url => {
  return url.indexOf("https://pluss60-dev-uploads.s3.ap-southeast-2.amazonaws.com/uploads/library") !== -1;
};
const getThumb300 = url => {
  if (!url) {
    return url;
  }
  if (isVideo(url)) {
    return "https://pluss60-demo-uploads.s3.ap-southeast-2.amazonaws.com/uploads/users/ap-southeast-2:97769b56-25ec-41c0-a73c-6c2c4140f629/public/9d0bbec64614b1ed654a03f7e7/movie.jpg";
  }
  if (url.indexOf("https://plussprdstorage.blob.core.windows.net/") !== -1) {
    return url.replace("https://plussprdstorage.blob.core.windows.net/", "https://plusscdn.azureedge.net/");
  }
  if (url.indexOf("https://plusscdn.azureedge.net/") !== -1) {
    return url.replace("/uploads/", "/uploads-thumb/").replace("/general/", "/general300/").replace("/uploads1400/", "/uploads-thumb/").replace("/general1400/", "/general300/");
  }
  if (isStockImage(url) || url.indexOf(Config.env.baseUploadsUrl) !== -1) {
    const extension = getExtension(url);
    let urlToUse = url;
    if (extension !== "jpg") {
      urlToUse = `${url.substring(0, url.length - extension.length)}jpg`;
    }
    return urlToUse.replace("/1400/", "/thumb300/").replace("/uploads/", "/thumb300/");
  }
  return url;
};
const get1400 = url => {
  if (!url) {
    return url;
  }
  if (url.indexOf("https://plussprdstorage.blob.core.windows.net/") !== -1) {
    return url.replace("https://plussprdstorage.blob.core.windows.net/", "https://plusscdn.azureedge.net/");
  }
  if (url.indexOf("https://plusscdn.azureedge.net/") !== -1) {
    return url.replace("/uploads/", "/uploads1400/").replace("/general/", "/general1400/");
  }
  if (isStockImage(url) || url.indexOf(Config.env.baseUploadsUrl) !== -1) {
    const extension = getExtension(url);
    let urlToUse = url;
    if (extension !== "jpg") {
      urlToUse = `${url.substring(0, url.length - extension.length)}jpg`;
    }
    return urlToUse.replace("/uploads/", "/1400/");
  }
  return url;
};
const get300 = url => {
  if (!url) {
    return url;
  }
  if (isStockImage(url) || url.indexOf(Config.env.baseUploadsUrl) !== -1) {
    const extension = getExtension(url);
    let urlToUse = url;
    if (extension !== "jpg") {
      urlToUse = `${url.substring(0, url.length - extension.length)}jpg`;
    }
    return urlToUse.replace("/uploads/", "/300/").replace("/1400/", "/300/");
  }
  return url;
};
const getMimeType = url => {
  const extension = getExtension(url);
  switch (extension) {
    case "mov":
      return "video/quicktime";
    case "mp4":
      return "video/mp4";
    default:
      return "image/jpeg";
  }
};
const getCompressed = url => {
  if (!url || typeof url !== "string") return "";
  return url.replace("/uploads/", "/compressed/");
};
const imageExists = url => {
  return new Promise(resolve => {
    fetch(url, {
      method: "HEAD",
      cache: "no-cache"
    }).then(response => {
      resolve(response.status === 200);
    }).catch(() => {
      resolve(false);
    });
  });
};
const formatTime = (hours, minutes) => {
  const period = hours >= 12 ? "pm" : "am";

  // Convert 24-hour format to 12-hour format
  const adjustedHours = hours > 12 ? hours - 12 : hours === 0 ? 12 : hours;

  // Ensure minutes are two digits
  const adjustedMinutes = String(minutes).padStart(2, "0");
  return `${adjustedHours}:${adjustedMinutes}${period}`;
};
const minutesToString = (minutes, isTimeOfDay) => {
  const hours = Math.floor(minutes / 60);
  const remainingMinutes = minutes % 60;
  if (isTimeOfDay) {
    return formatTime(hours, remainingMinutes);
  }
  const hoursString = hours > 1 ? `${hours} hours` : `${hours} hour`;
  const minutesString = remainingMinutes > 1 ? `${remainingMinutes} minutes` : `${remainingMinutes} minute`;
  if (hours && remainingMinutes) {
    return `${hoursString} ${minutesString}`;
  }
  if (hours) {
    return hoursString;
  }
  if (remainingMinutes) {
    return minutesString;
  }
  return "0 minutes";
};
const getPluralS = count => {
  return count === 1 ? "" : "s";
};
const getPluralOptions = (count, singular, plural) => {
  if (count === 1) {
    return singular;
  }
  return plural;
};
const isEmail = email => {
  if (_.isEmpty(email)) {
    return false;
  }
  const atpos = email.indexOf("@");
  const dotpos = email.lastIndexOf(".");
  if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= email.length) {
    return false;
  }
  return true;
};
const randomString = (name = "") => {
  return `xxxxxxxx4xxxyxxxxxxxxxxxxx${name}`.replace(/[xy]/g, c => {
    // eslint-disable-next-line
    var r = Math.random() * 16 | 0,
      v = c === "x" ? r : r & 0x3 | 0x8;
    return v.toString(16);
  });
};
const generateImageName = (name, source) => {
  let result = randomString(name);
  if (source) {
    result += `.${_.last(source.split("."))}`;
  }
  return result;
};
const getSite = site => {
  return site === "plussSpace" || site === "hq" ? Config.env.preferredSite : site;
};
const getTakeoverThumb = uri => {
  const filename = uri.split("/").pop();
  switch (filename) {
    default:
      return {
        uri
      };
  }
};
const getTakeoverImage = uri => {
  const filename = uri.split("/").pop();
  switch (filename) {
    default:
      return {
        uri
      };
  }
};
const getImageSource = (uri, isThumb) => {
  if (uri == null) return null;
  if (isThumb) return getTakeoverThumb(uri);
  return getTakeoverImage(uri);
};
const getFirstName = name => {
  if (_.isEmpty(name)) {
    return name;
  }
  return name.split(" ")[0];
};
const usersToSearchResult = (contacts, excludedUserIds) => {
  let result = [];
  contacts.forEach(user => {
    result.push({
      displayName: user.displayName,
      id: user.objectID || user.id || user.ID || user.userId || user.Id,
      profilePic: user.profilePic || user.photoURL || null,
      unit: user.unit
    });
  });
  result = _.reject(result, contact => {
    return _.includes(excludedUserIds, contact.id);
  });
  return result;
};
const searchUsers = (source, term) => {
  if (_.isEmpty(term)) {
    return source;
  }
  return _.filter(source, user => {
    const split = user.displayName.split(" ");
    return _.some(split, part => {
      return part.toLowerCase().indexOf(term.toLowerCase()) === 0;
    });
  });
};
const getTabSettingsFromState = state => {
  const tabSettings = state.user && state.user.interface || getSiteSettingFromState(state, "TabSettings", null);
  return tabSettings;
};
const getEnabledTabsFromState = state => {
  const tabSettings = getTabSettingsFromState(state);
  return tabSettings ? tabSettings.filter(tab => tab.isEnabled) : [];
};
const getReactions = () => {
  return [{
    key: "heart",
    icon: require("./assets/icons/reactions/heart.png")
  }, {
    key: "smile",
    icon: require("./assets/icons/reactions/smile.png")
  }, {
    key: "sad",
    icon: require("./assets/icons/reactions/sad.png")
  }, {
    key: "party",
    icon: require("./assets/icons/reactions/party.png")
  }];
};
const hasReacted = (reactions, userId) => {
  return _.some(reactions, r => {
    return !!r[userId];
  });
};
const isTablet = () => {
  return Dimensions.get("screen").width > 600;
};
const isVimeo = url => {
  if (_.isEmpty(url)) {
    return false;
  }
  if (url.indexOf("https://vimeo.com/") === 0) {
    return true;
  }
  if (url.indexOf("https://player.vimeo.com/video/") === 0) {
    return true;
  }
};
const getVimeoEmbed = url => {
  if (_.isEmpty(url)) {
    return "";
  }
  if (url.indexOf("https://vimeo.com/") === 0) {
    const vimeoId = "lol"; //TODO
    return `https://player.vimeo.com/video/${vimeoId}`;
  }
  return url; //TODO
};
const isYoutube = url => {
  if (_.isUndefined(url) || _.isEmpty(url)) {
    return false;
  }
  const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/;
  const match = url.match(regExp);
  if (match && match[2].length === 11) {
    return true;
  }
  return false;
};
const getYoutubeEmbed = url => {
  const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=|\?v=)([^#\&\?]*).*/;
  const match = url.match(regExp);
  return `https://www.youtube.com/embed/${match[2]}?autoplay=0`;
};
const getValidUrl = (url = "") => {
  let newUrl = decodeURIComponent(url);
  newUrl = newUrl.trim().replace(/\s/g, "");
  if (/^(:\/\/)/.test(newUrl)) {
    return `https${newUrl}`;
  }
  if (!/^(f|ht)tps?:\/\//i.test(newUrl)) {
    return `https://${newUrl}`;
  }
  return newUrl;
};
const getUserPreview = user => {
  return {
    id: user.uid,
    displayName: user.displayName,
    profilePic: user.profilePic || null
  };
};
const allowComments = canComment => {
  if (canComment === false) {
    return false;
  }
  if (canComment === true) {
    return true;
  }
  return Config.env.defaultAllowComments;
};
const toParagraphed = (text, style) => {
  if (!text) {
    return text;
  }
  const textSplit = text.split("\n");
  return _.map(textSplit, (t, i) => {
    return /*#__PURE__*/React.createElement(Text, {
      key: `paragraph_${i}`,
      style: style
    }, t);
  });
};
export { TIMESTAMP_FORMAT, DATE_FORMAT, getUrl, getAuthTokenHeader, getShadowStyle, StatusBarHeight, getStatusBarHeight, getSiteSettingFromState, getValueOrDefault, getExtension, getFileName, isVideo, get300, getThumb300, get1400, getMimeType, getCompressed, imageExists, getPluralS, getPluralOptions, isEmail, formatTime, minutesToString, randomString, generateImageName, getSite, getImageSource, getFirstName, usersToSearchResult, searchUsers, getEnabledTabsFromState, getReactions, hasReacted, isTablet, isYoutube, getYoutubeEmbed, getValidUrl, getUserPreview, allowComments, toParagraphed, isVideoUrl, detectFaces, findLandmarkRange, getScaledOffset, getSiteLevelFromState, isTVEnabled };
//# sourceMappingURL=helper.js.map