import { localStorageService } from './local_storage.service';
import { AnalyticsBase } from '../abstract/analytic_base.abstract';


export interface AnalyticsServiceInterface {
  event: (name: string, params: any) => void;
  optyConfigRef: { [key: string]: any };
}

export class AnalyticsService extends AnalyticsBase implements AnalyticsServiceInterface {
  public optyConfigRef: { [key: string]: any } = {};

  public fbq() {
    return {
      track: (name: string, data: any) => {
        window.fbq('track', name, data);
      },
    };
  }

  updateConfigOpty = (funnelAB: any) => {
    this?.optimizely?.onReady().then(() => {
      this.optyConfigRef = funnelAB.features.reduce((prev: any, current: string) => {
        if (this?.optimizely.isFeatureEnabled(current)) {
          prev[current] = this?.optimizely.getFeatureVariables(current);
        }
        return prev;
      }, {});

      if (this?.optyConfigRef?.web_general_single_flow_layout?.layout == 0) {
        localStorageService.setItem('web_general_single_flow_layout', 0);
      } else {
        localStorageService.setItem('web_general_single_flow_layout', 1);
      }
    });
  };

  public event(name: string, params = {}) {
    // @ts-ignore
    window?.dataLayer?.push({ event: name });

    void super.baseEvent(name, params);

    if (['OptimizelyExperimentViewed', 'OnboardingViewed'].includes(name)) return;

    try {
      this.optimizely?.onReady().then(() => {
        this.optimizely.track(name, this.userId);
      });
    } catch (error) {
      this.optimizely?.onReady().then(() => {
        this.optimizely.track(name, this.userId);
      });
    }
  }
}
