// import { styles } from '~comp/Notification/styles';
// import { Platform } from 'react-native';
// import { Crashlytics } from 'react-native-fabric';
// import firebase from 'react-native-firebase';
// import AppSee from 'react-native-appsee';
import FastImage from 'react-native-fast-image';

// const isAndroid = !(Platform.OS === 'ios');
import createLogger from 'react-native-log-level';
import { ToasterService } from 'nixplay-ui-kit';
import React from 'react';
import _ from 'lodash';
import moment from 'moment';

import { config } from '~/config';

// const FirebaseAnalytics = firebase.analytics();

export const log = createLogger(__DEV__ ? {
	level: 'trace', // Optionally set the log level. Defaults to 'info'
} : {
	level: 'warn',
});

// export const log = {
// 	trace: (msg, object) => {
// 		console.trace(`TRACE: ${msg} : ${JSON.stringify(object, null, 2)}`);
// 	},
// 	debug: (msg, object) => {
// 		console.trace(`DEBUG: ${msg} : ${JSON.stringify(object, null, 2)}`);
// 	},
// 	info: (msg, object) => {
// 		console.log(`INFO: ${msg} : ${JSON.stringify(object, null, 2)}`);
// 	},
// 	warn: (msg, object) => {
// 		console.log(`WARN: ${msg} : ${JSON.stringify(object, null, 2)}`);
// 	},
// 	error: (msg, object) => {
// 		console.log(`ERR: ${msg} : ${JSON.stringify(object, null, 2)}`);
// 		// if (isAndroid) {
// 		// 	Crashlytics.logException(`ERR: ${msg} : ${JSON.stringify(object, null, 2)}`);
// 		// } else {
// 		// 	Crashlytics.recordError(`ERR: ${msg} : ${JSON.stringify(object, null, 2)}`);
// 		// }
// 	},
// };

export const analytics = {
	setUserId: (userId) => {
		// FirebaseAnalytics.setUserId(userId.toString());
	},
	setUserProps: (userProps) => { // userProps = Object { prop1: prop1value, prop2: prop2value }
		// disabled due to stakeholders no go signal
		// _.forEach(userProps, (val, key) => {
		// 	FirebaseAnalytics.setUserProperty(key, val);
		// });
	},
	logEvent: (eventName, eventProps) => {
		// FirebaseAnalytics.logEvent(eventName, eventProps);
	},
	logAction: (actionName) => {
		// FirebaseAnalytics.logEvent(actionName);
	},
	firebaseProps: (userProps) => {
		_.forEach(userProps, (val, key) => {
			// FirebaseAnalytics.setUserProperty(key, val);
		});
	},
};

export const markViewAsSensitive = (el) => {
	if (_.isEmpty(el)) return;
};

export const showInAppNotification = (navigator, text) => {
	// const backgroundStyle = isError ? styles.error : styles.message;
	// const textStyle = isError ? styles.errorText : styles.messageText;
	log.warn('toast', text);
	ToasterService.toast({
		text,
	});
	// navigator.showInAppNotification({
	// 	screen: 'Nixplay.Notification',
	// 	passProps: {
	// 		text,
	// 		backgroundStyle,
	// 		textStyle,
	// 	},
	// 	autoDismissTimerSec: 1,
	// });
};


export const secondsToTimeString = (seconds) => {
	const roundedSec = Math.round(seconds);
	let s = roundedSec % 60;
	let m = Math.floor(roundedSec / 60);
	let strFormat = 'MM:SS';

	if (s < 10) s = `0${s}`;
	if (m < 10) m = `0${m}`;

	strFormat = strFormat.replace(/MM/, m);
	strFormat = strFormat.replace(/SS/, s);
	return strFormat;
};


export const humanFileSize = (byte, {
	withUnit = true, fromUnit = 'B', toUnit = null, fraction = 2, alwaysShowFraction = false,
}) => {
	const units = ['B', 'KB', 'MB', 'GB', 'TB'];
	const fromUnitIndex = units.indexOf(fromUnit) >= 0 ? units.indexOf(fromUnit) : 0;
	let unitIndex = 0;
	if (toUnit && units.indexOf(toUnit) >= 0) {
		unitIndex = units.indexOf(toUnit);
	} else if (byte > 0) {
		unitIndex = Math.floor(Math.log(byte) / Math.log(1024));
	}
	let num = byte;
	for (let i = fromUnitIndex; i < unitIndex; i += 1) { num /= 1024; }
	num = num.toFixed(fraction);
	if (!alwaysShowFraction) num *= 1;
	return withUnit ? `${num} ${units[unitIndex]}` : `${num}`;
};

export const percentage = (num, denom, comma = 2) => (
	denom > 0 ? (num / denom).toFixed(comma) * 100 : 0
);

/* eslint-disable */
export const debounceWrapper = (WrappedComponent) => {
	class PreventDoubleClick extends React.PureComponent {
		componentWillUnmount() {
			delete this.onPress;
		}

		debouncedOnPress = () => {
			if (this.props.onPress) this.props.onPress();
		};

		onPress = _.debounce(this.debouncedOnPress, (this.props.debounceTime ? this.props.debounceTime : 600), { leading: true, trailing: false });

		render() {
			return <WrappedComponent {...this.props} onPress={this.onPress} />;
		}
	}

	PreventDoubleClick.displayName = `debounceWrapper(${WrappedComponent.displayName || WrappedComponent.name})`;
	return PreventDoubleClick;
};
/* eslint-enable */

export const formatSerialDisplay = (serial) => (
	_.isEmpty(serial) ? '' : serial.match(/.{1,4}/g).join(' ')
);

export const getSpotifyLink = (isSpotifyInstalled, platform) => {
	if (isSpotifyInstalled) {
		return config.spotify.openLink;
	}
	if (platform === 'ios') {
		return config.spotify.appStoreLink;
	}
	return config.spotify.playStoreLink;
};

// returns object with values trimmed or returns empty string if undefined or null
export const getTrimmedValues = (values) => Object.keys(values).reduce((acc, key) => ({ ...acc, [key]: typeof values[key] === 'string' ? values[key].trim() : '' }), {});

export const trimValue = value => value && value.trim();

export const getTimeStampDifference = (endTimestamp, format = 'X', unit = 'days') => {
	const endDateTime = moment(endTimestamp, format);
	const currentTime = moment();
	return endDateTime.diff(currentTime, unit);
};

export const isMatchObjectWithKey = (target = {}, key = '', match) => {
	if (!_.isEmpty(target) && _.has(target, key)) {
		return (_.isEqual(target[key], match));
	}
	return false;
};

export const guestsOverLimit = (sharing, limit) => {
	const { contributors = [], invites = [] } = sharing || {};
	const isOverLimit = contributors.length + invites.length >= limit;
	if (isOverLimit) { analytics.logAction('sp_invite_reached_limit'); }
	return isOverLimit;
};

// export const isLangEn = () => {
// 	const { languageCode } = RNLocalize.getLocales()[0];
// 	return (_.isEqual(languageCode, 'en'));
// };

export const getSourceAvatar = (state, props = '', delimiter = '?', fullName = '') => {
	if (!_.isEmpty(fullName) && _.isEmpty(state)) {
		return { uri: `https://ui-avatars.com/api/?background=dfe7eb&color=466a77&name=${fullName}` };
	}
	const appendParams =
		(props === '' || _.isEqual(state, props)) ? `${delimiter}time=${(new Date()).getTime()}` : '';
	const source = (!_.isEmpty(state)) ?
		{
			uri: `${state}${appendParams}`,
			cache: FastImage.cacheControl.web,
			priority: FastImage.priority.high,
			headers: { Pragma: 'no-cache' },
		} : null;
	return source;
};
// export const getUnitPrices = (ShippingMethods) => (
// 	_.flatMap(ShippingMethods, ({ PricingGroups }) =>
// 		_.flatMap(PricingGroups, ({ PricingTierSets }) =>
// 			_.flatMap(PricingTierSets, ({ PricingTiers }) =>
// 				_.flatMap(PricingTiers, ({ UnitPrice }) => UnitPrice))))
// );

export const getUnitPrices = (ShippingMethods) => (
	_.flatMap(ShippingMethods, ({ PricingGroups }) =>
		_.flatMap(PricingGroups, ({ PricingTierSets }) =>
			_.flatMap(PricingTierSets, ({ IsSalePrice, PricingTiers, PricingTierSetName }) =>
				_.flatMap(PricingTiers, ({ UnitPrice }) => ({
					IsSalePrice,
					UnitPrice,
					PricingTierSetName,
				})))))
);

export const getLowestPricingTierSet = (ShippingMethods) => (
	_.flatMap(ShippingMethods, ({ PricingGroups }) =>
		_.flatMap(PricingGroups, ({ PricingTierSets }) => (PricingTierSets)))
);

export const getIsSalePrice = (ShippingMethods) => (
	_.flatMap(ShippingMethods, ({ PricingGroups }) =>
		_.flatMap(PricingGroups, ({ PricingTierSets }) =>
			_.flatMap(PricingTierSets, ({ IsSalePrice }) => IsSalePrice)))
);

export const getIsSalePriceTier = (ShippingMethods) => (
	_.flatMap(ShippingMethods, ({ PricingGroups }) =>
		_.flatMap(PricingGroups, ({ PricingTierSets }) =>
			_.flatMap(PricingTierSets, (PricingTierSet) => PricingTierSet)))
);

export const categoriesHasSaleProduct = (products) => (
	_.some(_.flatMap(products, product =>
		_.flatMap(product.ShippingMethods, ({ PricingGroups }) =>
			_.flatMap(PricingGroups, ({ PricingTierSets }) =>
				_.flatMap(PricingTierSets, ({ IsSalePrice }) => IsSalePrice)))))
);

export const getProductProperties = (product) => (
	_.has(product, 'Properties') ? _.chain(_.flatMap(product.Properties, Propertie => ({ ...Propertie })))
		.keyBy('Name')
		.mapValues('Value')
		.value() : []
);

// export const printableItem = (photo) => _.isEqual(photo.mediaType, 'photo') && (!_.includes(photo.photoUrl, 'sns') && !_.includes(photo.thumbnailUrl, 'sns'));
export const printableItem = (photo) => _.isEqual(photo.mediaType, 'photo');


export const getCategorySpecs = (a, b) => (
	_.merge(_.sortBy(_.filter(a, (n) =>
		_.findIndex(b, f => (_.isEqual(n.ID, f.ID) && f.isParetnCategory === true)) !== -1), (e) =>
		_.findIndex(b, f => _.isEqual(e.ID, f.ID))), _.filter(b, (x) => _.isEqual(x.isParetnCategory, true)))
);

export const getSubCategorySpecs = (a, b) => (
	_.merge(a, _.sortBy(_.filter(b, (n) =>
		_.findIndex(a, f => (_.isEqual(n.ID, f.ID) && n.isParetnCategory === false)) !== -1), (e) =>
		_.findIndex(b, f => _.isEqual(e.ID, f.ID))))
);
