// Added EsLint Disable because it is looking for ErrorUtils that is already global in RN
// and the _globalHandler will trigger underscore dangle, but this is predefined

/* eslint-disable */
// import firebase from 'react-native-firebase';
import { store } from '~/store/store';
import { Platform } from 'react-native';

const defaultHandler = (ErrorUtils.getGlobalHandler &&
ErrorUtils.getGlobalHandler()) || ErrorUtils._globalHandler;

function convertToString(arg) {
	return typeof arg === 'object' ? JSON.stringify(arg) : `${arg}`;
}

/*eslint-disable*/
handleJSLogs = () => {
	['error', 'warn', 'log'].forEach((methodName) => {
		const origMethod = console[methodName];
		console[methodName] = (...args) => {
			if (args.length > 1) {
				console.warn(`react-native-fabric supports only 1 (one) argument to method and have passed <${args.length}> arguments. Replace this line by "console.trace()" to see stack trace`);
			}
			if (args.some(arg => typeof arg !== 'string')) {
				console.warn(`It seems that some argument type is not <string> on <${JSON.stringify(args)}>. Converting it to string.`);
			}
			const message = convertToString(args.shift());

			if (Platform.OS === 'android') {
				// firebase.crashlytics().log(message);
			}
			origMethod.call(console, message);
			console[methodName].name = `decoratedConsole_${methodName}`;
		};
	})
}


/*eslint-disable*/
handleUncaughtErrors = () => {
	console.log('App is handling uncaught errors');
	if (ErrorUtils) {
		ErrorUtils.setGlobalHandler((error, isFatal) => {
			console.log(`Handle error. Is fatal? <${isFatal}>`);
			error.message = `ErrorUtils: handled ${isFatal ? 'fatal':'non-fatal'} error: ${error.message}`;
			const {
				userProfileId
			} = store.getState().user;

			if (userProfileId) {
				// firebase.crashlytics().setUserIdentifier(userProfileId.toString());
			}

			// firebase.crashlytics().log(error.stack);

			if (isFatal) {
				// firebase.crashlytics().recordError(error);
				console.log('reboot the app');
			} else {
				// firebase.crashlytics().logException(error);
				// firebase.crashlytics().recordError(0, 'non-fatal');
			}
			if (defaultHandler) {
				defaultHandler(error, isFatal);
			}
		});
	}
}

// handlePromiseRejections = () => {
// 	console.log('App is handling promise rejections');
// 	const tracking = require('promise/setimmediate/rejection-tracking');
// 	tracking.enable({
// 		allRejections: true,
// 		onUnhandled: function(id, error) {
// 			console.log('Handle promise rejection');
// 			firebase.crashlytics().log(error.stack);
// 			error.message = `handlePromiseRejections: handled promise rejection: ${error.message}`;
// 			firebase.crashlytics().recordError(error);
// 		},
// 		onHandled: function() {}
// 	});
// }

export const setJsExceptionHandler = () => {
	handleJSLogs();
	handleUncaughtErrors();
	// handlePromiseRejections();
	console.log('App is running decorated console methods');
};
