import {ExceptionObject} from "./typings";
import {toISOLocal} from "../utils";
import CfCore from "./CfCore";
import {Nudge} from "./repositories/nudges/typings";
import {NotificationAction} from "../drivers/notifications/typings";
import Navigation from "../modules/Navigation/index";
import {NudgeAction} from "../modules/Navigation/typings";


export default class CfExceptionHandler {
    throwAndLogError(eventName: string, msg: string) {

        const error = new Error(msg)
        const exceptionObject: ExceptionObject = {
            title: msg,
            event_type: eventName,
            exception_type: error.name,
            exception_source: 'JS-SDK',
            stack_trace: error.stack || 'no stack',
            ts: toISOLocal(new Date())
        }

        CfCore.getInstance().trackExceptionEvent([exceptionObject])


        throw error;
    }

    throwAPIError(eventName: string, msg: string) {

        const error = new Error(msg)
        const exceptionObject: ExceptionObject = {
            title: msg,
            event_type: eventName,
            exception_type: error.name,
            exception_source: 'JS-SDK',
            stack_trace: error.stack || 'no stack',
            ts: toISOLocal(new Date())
        }

        CfCore.getInstance().trackExceptionEvent([exceptionObject])
    }

    throwNudgeFetchError(eventName: string, msg: string) {

        const error = new Error(msg)
        const exceptionObject: ExceptionObject = {
            title: msg,
            event_type: eventName,
            exception_type: error.name,
            exception_source: 'JS-SDK',
            stack_trace: error.stack || 'no stack',
            ts: toISOLocal(new Date())
        }

        CfCore.getInstance().trackExceptionEvent([exceptionObject])
    }

    throwNudgeException(msg: string, nudge: Nudge) {

        Navigation.logPushNotificationEvent({
            ref: nudge.ref,
            response: NudgeAction.Error,
            time: nudge.time,
            details: msg
        })

        const exceptionObject: ExceptionObject = {
            title: msg,
            event_type: 'nudge_response',
            exception_type: "IllegalArgumentException",
            exception_source: 'JS-SDK',
            stack_trace: "Nudge Object:"+ JSON.stringify(nudge),
            ts: toISOLocal(new Date())
        }

        CfCore.getInstance().trackExceptionEvent([exceptionObject])

    }

}
