ricardofanetto
2/28/2020 - 10:33 AM

analytics

import { ConfigHelper } from './../../app/helpers/configHelper';
import { UserAuthenticatedModel } from './../../app/models/userAuthenticatedModel';
import { UserProvider } from './../user/user';
import { Firebase } from '@ionic-native/firebase';
import { Injectable } from '@angular/core';
import { Events, Platform } from 'ionic-angular';
import { ENV } from '@app/env';

export enum TypeEvent {
  log,
  error
}

@Injectable()
export class AnalyticsProvider {

  private currentUser: UserAuthenticatedModel

  constructor(
    private firebase: Firebase,
    private platform: Platform,
    private evt: Events) {
    this.registerUser()
    this.evt.subscribe(ConfigHelper.Events.loginChange, () => this.registerUser());
  }

  private async registerUser() {
    if (!ENV.production) return
    this.currentUser = UserProvider.user
    this.platform.ready().then(async () => {
      if (this.platform.is('cordova')) {
        await this.firebase.setUserId(this.currentUser.name);
        await this.firebase.setUserProperty('name', this.currentUser.name)
        await this.firebase.setUserProperty('company', this.currentUser.companyName)
      }
    })
  }

  public async registerScreen(screen: string): Promise<void> {
    if (!ENV.production) return
    this.platform.ready().then(async () => {
      if (this.platform.is('cordova')) {
        await this.firebase.setScreenName(screen);
      }
    })
  }

  public async registerEvent(type: TypeEvent, eventName: string, params?: any): Promise<void> {
    if (!ENV.production) return
    this.platform.ready().then(async () => {
      if (this.platform.is('cordova')) {
        if (type === TypeEvent.log)
          await this.firebase.logEvent(eventName, params)
        else
          await this.firebase.logError(params)
      }
    })
  }
}