import cleaninsights from "./cleaninsights.service";
import { Config } from "./config.service";
import matomo from "./matomo.service";

export interface AnalyticsEngine {
  event(category: string, action: string): void;
}

type AnalyticsEvent = {
  category: string;
  action: string;
}

export default {
  install(app: any) {
    class AnalyticsServiceClass {
      
      engines: AnalyticsEngine[];
      cachedEvents: AnalyticsEvent[];
      initialized: boolean;

      constructor() {
        this.engines = [];
        this.cachedEvents = [];
        this.initialized = false;

        app.$config.load().then((config: Config) => {
          var analytics = config.analytics || {};
          if (!Array.isArray(analytics)) {
            analytics = [analytics];
          }
          for (const engineConfig of analytics) {
            if (engineConfig.enabled) {
              let type = engineConfig.type || "ci";
              switch (type) {
                case "ci":
                  {
                    let engine = cleaninsights.install(app, engineConfig.config);
                    this.engines.push(engine);
                  }
                  break;
                case "matomo":
                  {
                    let engine = matomo.install(app, engineConfig.config);
                    this.engines.push(engine);
                  }
                  break;
              }
            }
          }

          this.initialized = true;

          // Handle cached events
          this.cachedEvents.forEach(({category, action}) => {
            this.event(category, action);
          });
          this.cachedEvents = [];
        });
      }

      event(category: string, action: string) {
        if (!this.initialized) {
          this.cachedEvents.push({category, action});
          return;
        }

        // Send the event to each configured analytics engine.
        this.engines.forEach((engine) => {
          engine.event(category, action);
        });
      }
    }

    const analyticsService = new AnalyticsServiceClass();
    app.$analytics = analyticsService;
    app.config.globalProperties.$analytics = analyticsService;
  },
};
