package com.contentsquare.plugins.capacitor;

import java.lang.reflect.Method;

public class ContentsquareCAPTelemetry {

    private final String XPF_TYPE = "CAPACITOR";
    private final String UNKNOWN_XPF_VERSION = "UNKNOWN";

    private final Object telemetryInstance;
    private final Class<?> telemetryInterface;
    private Method telemetryCollect;
    private Method telemetrySetXPFVersion;
    private Method telemetrySetXPFType;

    /**
     * The default constructor
     * @throws Exception
     */
    public ContentsquareCAPTelemetry() throws Exception {

        telemetryInterface = Class.forName("com.contentsquare.android.api.bridge.telemetry.TelemetryInterface");
        telemetryInstance = telemetryInterface.newInstance();

        Method[] declaredMethods = telemetryInterface.getDeclaredMethods();

        for (Method method : declaredMethods) {
            if (method.getName().equals("telemetryCollect")) {
                telemetryCollect = method;
            } else if (method.getName().equals("telemetrySetXPFVersion")) {
                telemetrySetXPFVersion = method;
            } else if (method.getName().equals("telemetrySetXPFType")) {
                telemetrySetXPFType = method;
            }
        }

    }


    /**
     * Collect telemetry information with key/label values
     *
     * @param name name of the information to collect
     * @param value value of the information to collect
     * @throws Exception
     */
    public void collect(String name, String value) throws Exception {
        telemetryCollect.invoke(telemetryInstance, name, value);
    }

    /**
     * Set the Capacitor framework version
     *
     * @param capacitorVersion The Capacitor framework version used by the application
     * @throws Exception
     */
    public void setXPFVersion(String capacitorVersion) throws Exception {
        telemetrySetXPFVersion.invoke(telemetryInstance, capacitorVersion);
    }

    /**
     * Set the Framework type (CAPACITOR)
     * @throws Exception
     */
    public void setXPFType() throws Exception {
        telemetrySetXPFType.invoke(telemetryInstance, XPF_TYPE);
    }

    private String getCapacitorVersion() {
        return UNKNOWN_XPF_VERSION;
    }

}
