import { getOdpTrackingScript } from "@insite/client-framework/Common/Utilities/odpTracking";
import { createHandlerChainRunnerOptionalParameter, Handler } from "@insite/client-framework/HandlerCreator";
import { getIsShareEntity } from "@insite/client-framework/ServerSideRendering";
import { Session } from "@insite/client-framework/Services/SessionService";
import { SettingsModel } from "@insite/client-framework/Services/SettingsService";

type HandlerType = Handler<{}, { session: Session; settings: SettingsModel }>;

export const LookUpData: HandlerType = props => {
    const state = props.getState();

    if (
        IS_SERVER_SIDE ||
        !state.context.settings.settingsCollection.websiteSettings.enableOdpStorefrontEvents ||
        getIsShareEntity()
    ) {
        return false;
    }

    props.session = state.context.session;
    props.settings = state.context.settings;
};

export const SetOdpTrackingScript: HandlerType = ({ settings }) => {
    const odpTrackingScript = getOdpTrackingScript(settings.settingsCollection.websiteSettings.odpJsTagUrl);
    if (odpTrackingScript) {
        let odpScript = document.getElementById("odpTrackingScript");
        if (!odpScript) {
            odpScript = document.createElement("script");
            odpScript.setAttribute("id", "odpTrackingScript");
            odpScript.innerHTML = odpTrackingScript;
            document.head.appendChild(odpScript);
        }
    }
};

export const chain = [LookUpData, SetOdpTrackingScript];

export const setOdpTracking = createHandlerChainRunnerOptionalParameter(chain, {}, "SetOdpTracking");
