export interface LogglyConfigInterface {
    key: string
    host: string
    sendConsoleErrors: boolean
    tag: string
    appVersion: string
}

export class LogglyLogger {

    private _globalObject: any = {}
    private _url: string

    /**
     * There is no window in a service worker so we need to
     * check for the existence of a global object
     */
    constructor(
        private _config: LogglyConfigInterface,
    ) {
        this._setUrl()
        this._globalObject = window
    }

    public log(data: any) {
        const type = typeof data
        if (!data || !(type === 'object' || type === 'string')) {
            console.log(`Cannot send data of type ${type} to loggly`)
            return
        }

        if (type === 'string') data = { text: data }

        // ensure the app version is in every log
        data.appVersion = this._config.appVersion

        try {
            // creating an asynchronous XMLHttpRequest
            const xmlHttp = new XMLHttpRequest()
            xmlHttp.open('POST', this._url, true) // true for asynchronous request
            xmlHttp.setRequestHeader('Content-Type', 'text/plain')
            xmlHttp.send(JSON.stringify(data))

        } catch (e) {
            if (console && typeof console.log === 'function') {
                console.log(`Failed to log to loggly because of this exception:\n${e}`)
                console.log('Failed log data:', data)
            }
        }
    }

    public _setUrl() {
        return this._url = `https://${this._config.host}/inputs/${this._config.key}/tag/${this._config.tag}`
    }

    public _setSendConsoleError() {
        if (this._config.sendConsoleErrors) {
            // send console error messages to Loggly
            this._globalObject.onerror = function(msg: any, url: any, line: any, col: any) {
                this.log({
                    category: 'BrowserJsException',
                    exception: {
                        message: msg,
                        url,
                        lineno: line,
                        colno: col,
                    },
                })
            }
        }
    }
}
