/*
 * author: Lisa
 * Info: error handler
 */

import React, {Component} from 'react';
var {
	PropTypes,
} = require('react-native');

function monitorError(callback){
	var errorHandleDidEnd = function(errorMessage){
		if(callback){
			callback(errorMessage);
		}
	};
	require('fbjs/lib/ErrorUtils').setGlobalHandler(function(error) {
		var errorMessage = '[' + error.name + '] ' + error.message + '\n';
		const parseErrorStack = require('react-native/Libraries/JavaScriptAppEngine/Initialization/parseErrorStack');
		require('react-native/Libraries/JavaScriptAppEngine/Initialization/SourceMapsCache').getSourceMaps().then(sourceMaps => {
			const prettyStack = parseErrorStack(error, sourceMaps);
			var stackMessage = prettyStack.map((stack) => {
				var lineNum = stack.lineNumber;
				var column = stack.column;
				var file = stack.file;
				var methodName = stack.methodName;
				return file + ' @ ' + lineNum + ':' + column;
			}).join('\n');
			errorMessage = errorMessage + stackMessage;
			errorHandleDidEnd(errorMessage);
		}).catch(error => {
			errorMessage = errorMessage + '[!] Unable to load source map';
			errorHandleDidEnd(errorMessage);
		});
	});
}

exports.logType = 'app_error';
exports.monitorError = monitorError;
