import AsyncStorage from '@react-native-async-storage/async-storage';
import moment from 'moment';
import {Linking} from 'react-native';
import config from '../config';
import RNRestart from 'react-native-restart';
const storeData = async (storageKey, value) => {
  try {
    const jsonValue = JSON.stringify(value);
    await AsyncStorage.setItem(storageKey, jsonValue);
  } catch (e) {
    // saving error
  }
};

const getData = async storageKey => {
  try {
    const jsonValue = await AsyncStorage.getItem(storageKey);
    return jsonValue != null ? JSON.parse(jsonValue) : null;
  } catch (e) {
    // error reading value
  }
};
const removeData = async storageKey => {
  try {
    await AsyncStorage.removeItem(storageKey);
  } catch (e) {
    // error reading value
  }
};

// const startTime = new Date('2023-03-16T12:55:00+07:00');
const calculateElapsedSeconds = (eventDate, eventTime) => {
  const eventDateTime = moment(
    `${eventDate.split('T')[0]}T${eventTime ?? '13:00:00'}`,
  );
  const now = moment();
  const elapsedSeconds = Math.max(eventDateTime.diff(now, 'seconds'), 0) - 300;
  return elapsedSeconds <= 0 ? 0 : elapsedSeconds;
};

/**
 * Nested Object or Array data value retriever
 * @param source
 * @param variables {string}
 * @param fallbackValue {any}
 * @param allowNull
 * @returns {any|boolean|string}
 */
const getValues = (
  source,
  variables = '',
  fallbackValue,
  allowNull = false,
) => {
  const targetValueHierarchy = (variables || '')
    .toString()
    .replace(/[[\]]/g, '.')
    .split('.')
    .filter(key => key !== '');

  if (source === null && allowNull && targetValueHierarchy.length === 0) {
    return null;
  }

  // Check for string type because string is subtype of Array
  // Don't worry, if the data type not an object or array will fail after that.
  if (!source || ['string, boolean'].includes(typeof source)) {
    return fallbackValue;
  }

  // Retain data type cause data type is dynamic
  let result = Object.assign(source);

  for (let i = 0; i < targetValueHierarchy.length; i++) {
    result = result[targetValueHierarchy[i]];

    if (result === undefined) {
      break;
    }

    if (result === null && i !== targetValueHierarchy.length - 1) {
      result = undefined;
      break;
    }
  }

  if (result === null) {
    return allowNull ? result : fallbackValue;
  }

  return result !== undefined ? result : fallbackValue;
};

const formatLinkYoutube = url => {
  var regExp =
    /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#&?]*).*/;
  var match = url.match(regExp);
  return match && match[7].length == 11 ? match[7] : '';
};

const handleOpenUrl = async url => {
  // Checking if the link is supported for links with custom URL scheme.
  const supported = await Linking.canOpenURL(url);
  if (supported) {
    // Opening the link with some app, if the URL scheme is "http" the web link should be opened
    // by some browser in the mobile
    await Linking.openURL(url);
  }
};
const formatMonthVietNamLanguage = month => {
  const months = [
    {
      en: 'January',
      vi: 'Tháng 1',
    },
    {
      en: 'February',
      vi: 'Tháng 2',
    },
    {
      en: 'March',
      vi: 'Tháng 3',
    },
    {
      en: 'April',
      vi: 'Tháng 4',
    },
    {
      en: 'May',
      vi: 'Tháng 5',
    },
    {
      en: 'June',
      vi: 'Tháng 6',
    },
    {
      en: 'July',
      vi: 'Tháng 7',
    },
    {
      en: 'August',
      vi: 'Tháng 8',
    },
    {
      en: 'September',
      vi: 'Tháng 9',
    },
    {
      en: 'October',
      vi: 'Tháng 10',
    },
    {
      en: 'November',
      vi: 'Tháng 11',
    },
    {
      en: 'December',
      vi: 'Tháng 12',
    },
  ];
  const viMonth = months.filter(item => item.en === month);
  return viMonth[0].vi;
};

const formatCurrency = price => {
  if (!price || !Number(price)) return;
  return price.toLocaleString('vi', {style: 'currency', currency: 'VND'});
};
const getCategoryNotification = category => {
  return Object.keys(config.categoryNotification).find(el => el === category);
};
const minutesToHours = (start, finish) => {
  //console.log(start, finish);
  if (!start || !finish) return '00:00';
  let time = moment(finish).diff(moment(start), 'minutes');
  var Hours = Math.floor(time / 60);
  var minutes = time % 60;
  return `${Hours}:${minutes} giờ`;
};
const restartApp = () => RNRestart.Restart();
const Utils = {
  storeData,
  getData,
  removeData,
  calculateElapsedSeconds,
  getValues,
  formatLinkYoutube,
  handleOpenUrl,
  formatMonthVietNamLanguage,
  formatCurrency,
  getCategoryNotification,
  minutesToHours,
  restartApp,
};
export default Utils;
