import { createHandlerChainRunnerOptionalParameter, Handler } from "@insite/client-framework/HandlerCreator";

type HandlerType = Handler<{}, { websiteFavicon: string }>;

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

    if (IS_SERVER_SIDE) {
        return false;
    }

    props.websiteFavicon = state.context.website.websiteFavicon;
};

export const SetFaviconIfRequired: HandlerType = ({ websiteFavicon }) => {
    if (!websiteFavicon) {
        return;
    }

    let iconLink = document.querySelector('link[rel="icon"]');
    if (!iconLink) {
        iconLink = document.createElement("link");
        iconLink.setAttribute("rel", "icon");
        iconLink.setAttribute("href", websiteFavicon);
        iconLink.setAttribute("type", "image/x-icon");
        document.head.appendChild(iconLink);
    } else {
        iconLink.setAttribute("href", websiteFavicon);
    }

    let appleIconLink = document.querySelector('link[rel="apple-touch-icon image_src"]');
    if (!appleIconLink) {
        appleIconLink = document.createElement("link");
        appleIconLink.setAttribute("rel", "apple-touch-icon image_src");
        appleIconLink.setAttribute("href", websiteFavicon);
        document.head.appendChild(appleIconLink);
    } else {
        appleIconLink.setAttribute("href", websiteFavicon);
    }
};

export const chain = [LookUpData, SetFaviconIfRequired];

export const setFavicon = createHandlerChainRunnerOptionalParameter(chain, {}, "SetFavicon");
