import {make, Middleware, Injectable, Inject, SecurityContext, Logging, Config} from '@extollo/lib'
import * as PageViewModule from '../../models/PageView.model'

/**
 * PageView Middleware
 * --------------------------------------------
 * Record the page view to the analytics table.
 */
@Injectable()
export class PageView extends Middleware {
    @Inject()
    protected readonly security!: SecurityContext

    @Inject()
    protected readonly logging!: Logging

    @Inject()
    protected readonly config!: Config

    public async apply() {
        if ( this.request.cookies.has(this.config.get('app.analytics.optOutCookie')) ) {
            return
        }

        const view = make<PageViewModule.PageView>(PageViewModule.PageView)
        const user = this.security.getUser()

        const realIp = this.request.getHeader('X-GM-Real-IP')

        // hostname
        view.ip = `${this.getIP()}:${this.request.address.port}`
        view.method = this.request.method
        view.endpoint = this.request.path
        view.userId = user ? (user as any).userId : undefined
        view.xhr = this.request.isXHR

        this.logging.debug(this.request)

        await view.save()
    }

    private getIP(): string {
        const realIp = this.request.getHeader('X-GM-Real-IP')
        if ( !realIp ) {
            return this.request.address.address
        }

        if ( Array.isArray(realIp) ) {
            return realIp[0] || this.request.address.address
        }

        return realIp
    }
}
