/**
 * Copyright (c) 2021, WSO2 Inc. (http://www.wso2.com). All Rights Reserved.
 *
 * This software is the property of WSO2 Inc. and its suppliers, if any.
 * Dissemination of any information or reproduction of any material contained
 * herein in any form is strictly forbidden, unless permitted by WSO2 expressly.
 * You may not alter or remove any copyright or other notice from copies of this content."
 */

import { AlertInterface, AlertLevels, TestableComponentInterface } from "@wso2is/core/models";
import { addAlert } from "@wso2is/core/store";
import { EncodeDecodeUtils } from "@wso2is/core/utils";
import { CodeEditor, Heading, Text } from "@wso2is/react-components";
import isEmpty from "lodash/isEmpty";
import React, { FunctionComponent, ReactElement, ReactNode, useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { Button, Divider, DropdownItemProps, Form, Icon, List, Message } from "semantic-ui-react";
import {
    createNewKeyStoreCode,
    dotNetSDKConfigCode,
    dotNetSDKLoginCode,
    dotNetSDKLogoutCode,
    dotNetSDKNugetCLICode,
    importCertificateCode,
    tomcatOIDCAgentLoginButtonCode,
    tomcatOIDCAgentLogoutCode,
    tomcatOIDCAgentMavenDependencyCode,
    tomcatOIDCAgentSamplePropertiesCode,
    tomcatOIDCAgentSampleWebXMLCode,
    tomcatOIDCJKSSamplePropertiesCode,
    wso2InternalRepoPointingCode
} from "./code-blocks";
import { SDKMeta } from "./meta";
import { SupportedTraditionalOIDCAppTechnologyTypes } from "./models";
import {
    ApplicationInterface,
    ApplicationManagementUtils,
    ApplicationTemplateInterface, OIDCDataInterface, SupportedAuthProtocolTypes, updateAuthProtocolConfig
} from "../../../../features/applications";
import { Config } from "../../../../features/core/configs";
import { ConfigReducerStateInterface } from "../../../../features/core/models";
import { AppState } from "../../../../features/core/store";
import {
    VerticalStepper,
    VerticalStepperStepInterface
} from "../../../components/component-extensions/application/vertical-stepper";

interface IntegrateSDKsPropsInterface extends TestableComponentInterface {
    application: ApplicationInterface;
    technology: SupportedTraditionalOIDCAppTechnologyTypes;
    template: ApplicationTemplateInterface;
    inboundProtocolConfig: any;
}

/**
 * Integrate SDKs to Single Page Applications.
 *
 * @param {IntegrateSDKsPropsInterface} props - Props injected into the component.
 * @return {React.ReactElement}
 */
export const IntegrateSDKs: FunctionComponent<IntegrateSDKsPropsInterface> = (
    props: IntegrateSDKsPropsInterface
): ReactElement => {

    const {
        application,
        inboundProtocolConfig,
        technology,
        [ "data-testid" ]: testId
    } = props;

    const dispatch = useDispatch();

    const config: ConfigReducerStateInterface = useSelector((state: AppState) => state.config);

    const [ SDKInitConfig, setSDKInitConfig ] = useState(undefined);
    const [ configuredCallbacks, setConfiguredCallbacks ] = useState<DropdownItemProps[]>([]);
    const [ selectedLoginCallBack, setSelectedLoginCallBack ] = useState<any>("");
    const [ selectedLogoutCallBack, setSelectedLogoutCallBack ] = useState<any>("");
    const [ sampleServerHost, setSampleServerHost ] = useState<string>(null);
    const [ callbacksUpdated, setCallbacksUpdated ] = useState<boolean>(false);

    useEffect(() => {

        if (!inboundProtocolConfig?.oidc?.callbackURLs
            || !Array.isArray(inboundProtocolConfig.oidc.callbackURLs)
            || inboundProtocolConfig.oidc.callbackURLs.length < 1) {

            return;
        }

        const callbacks: string[] = EncodeDecodeUtils.decodeURLRegex(inboundProtocolConfig.oidc.callbackURLs[ 0 ]);

        if (callbacks && Array.isArray(callbacks) && callbacks.length > 1) {
            callbacks.forEach((url: string) => {
                setConfiguredCallbacks((prevItems) => [
                    ...prevItems,
                    {
                        key: url,
                        text: url,
                        value: url
                    }
                ]);
            });
        }
    }, [ inboundProtocolConfig ]);

    useEffect(() => {
        if (!inboundProtocolConfig?.oidc) {
            return;
        }

        const configs = {
            clientID: inboundProtocolConfig.oidc.clientId,
            clientSecret: inboundProtocolConfig.oidc.clientSecret,
            serverOrigin: Config.getDeploymentConfig().serverHost,
            signInRedirectURL: (configuredCallbacks.length > 1)
                ? selectedLoginCallBack
                : inboundProtocolConfig.oidc.callbackURLs[ 0 ],
            signOutRedirectURL: (configuredCallbacks.length > 1)
                ? selectedLogoutCallBack
                : inboundProtocolConfig.oidc.callbackURLs[ 0 ]
        };

        setSDKInitConfig(configs);
    }, [ inboundProtocolConfig, configuredCallbacks, selectedLoginCallBack, selectedLogoutCallBack ]);

    const handleAddCallback = (url: string) => {

        const configuredCallbacks: any = ApplicationManagementUtils.buildCallBackURLWithSeparator(
            inboundProtocolConfig.oidc.callbackURLs[ 0 ]).split(",");

        const shouldUpdateCallbacks: boolean = !configuredCallbacks.includes(url);
        const shouldUpdateAllowedOrigins: boolean = !inboundProtocolConfig.oidc.allowedOrigins.includes(url);

        const body: OIDCDataInterface = {
            ...inboundProtocolConfig.oidc,
            allowedOrigins: shouldUpdateAllowedOrigins
                ? [ ...inboundProtocolConfig.oidc.allowedOrigins, url ]
                : inboundProtocolConfig.oidc.allowedOrigins,
            callbackURLs: shouldUpdateCallbacks
                ? [ ApplicationManagementUtils.buildCallBackUrlWithRegExp([ ...configuredCallbacks, url ].join(",")) ]
                : inboundProtocolConfig.oidc.callbackURLs
        };

        const resolveAlertContent = () => {

            if (shouldUpdateAllowedOrigins && shouldUpdateCallbacks) {
                return {
                    description: "Successfully updated the URLs in the application.",
                    level: AlertLevels.SUCCESS,
                    message: "Updated the URLs"
                };
            } else if (shouldUpdateCallbacks) {
                return {
                    description: "Successfully updated the Allowed Origins.",
                    level: AlertLevels.SUCCESS,
                    message: "Updated the URLs"
                };
            }

            return {
                description: "Successfully updated the Callback URLs in the application.",
                level: AlertLevels.SUCCESS,
                message: "Updated the URLs"
            };
        };

        updateAuthProtocolConfig(application.id, body, SupportedAuthProtocolTypes.OIDC)
            .then(() => {
                setCallbacksUpdated(true);

                dispatch(addAlert<AlertInterface>(resolveAlertContent()));
            })
            .catch(() => {
                dispatch(addAlert<AlertInterface>({
                    description: "An error occurred while updating the application.",
                    level: AlertLevels.ERROR,
                    message: "Error occurred"
                }));
            });
    };

    const checkCallbacks = (urlToCheck: string) => {
        const urlArray = inboundProtocolConfig.oidc
            ? EncodeDecodeUtils.decodeURLRegex(inboundProtocolConfig.oidc.callbackURLs[ 0 ])
            : [];

        if (!urlArray || !Array.isArray(urlArray) || urlArray.length < 1) {

            return false;
        }

        return urlArray.includes(urlToCheck);
    };

    const generateConfigureStepTitle = (technology: SupportedTraditionalOIDCAppTechnologyTypes): ReactNode => {

        if (technology === SupportedTraditionalOIDCAppTechnologyTypes.TOMCAT_OIDC_AGENT) {
            return "Add Dependencies";
        }

        if (technology === SupportedTraditionalOIDCAppTechnologyTypes.DOT_NET) {
            return "Installing the SDK";
        }

        return "Configure SDK";
    };

    const generateConfigureStep = (technology: SupportedTraditionalOIDCAppTechnologyTypes): ReactNode => {

        if (technology === SupportedTraditionalOIDCAppTechnologyTypes.TOMCAT_OIDC_AGENT) {
            return (
                <>
                    <Text>
                        To ease the developers, we&apos;ve introduced the <a
                            href="https://github.com/asgardeo/asgardeo-tomcat-oidc-agent"
                            target="_blank"
                            rel="noopener noreferrer"
                            className="link external"
                        >Asgardeo OIDC Agent</a>. You can use this Agent in your project by updating
                        your <code className="inline-code">pom.xml</code> file with the following dependency.
                    </Text>

                    <div className="code-segment">
                        <CodeEditor
                            readOnly
                            showLineNumbers
                            withClipboardCopy
                            height="100%"
                            language="htmlmixed"
                            sourceCode={ tomcatOIDCAgentMavenDependencyCode() }
                            options={ {
                                lineWrapping: true
                            } }
                            theme="dark"
                        />
                    </div>

                    <Divider hidden />

                    <Text>
                        The SDK is hosted at the <strong>WSO2 Internal Repository</strong>.
                        Point to the repository as follows.
                    </Text>

                    <div className="code-segment">
                        <CodeEditor
                            readOnly
                            showLineNumbers
                            withClipboardCopy
                            language="htmlmixed"
                            sourceCode={ wso2InternalRepoPointingCode() }
                            options={ {
                                lineWrapping: true
                            } }
                            theme="dark"
                        />
                    </div>
                </>
            );
        }

        if (technology === SupportedTraditionalOIDCAppTechnologyTypes.DOT_NET) {
            return (
                <>
                    <Text>
                        You can download the SDK using <strong>Nuget Package Manger</strong> by following the steps
                        below.
                    </Text>

                    <List ordered>
                        <List.Item>
                            Open the <a
                            href="https://www.nuget.org/"
                            target="_blank"
                            rel="noopener noreferrer"
                            className="link external"
                            >Nuget Package Manger</a>.
                        </List.Item>
                        <List.Item>
                            Search for <code className="inline-code">Asgardeo.OIDC.SDK</code>.
                        </List.Item>
                        <List.Item>
                            Include it with the suggested required dependencies for the project/solution.
                        </List.Item>
                    </List>

                    <Text>
                        Alternatively, you can also run the following command in the Package Manager CLI as shown below.
                    </Text>

                    <div className="code-segment">
                        <CodeEditor
                            readOnly
                            oneLiner
                            withClipboardCopy
                            language="htmlmixed"
                            sourceCode={ dotNetSDKNugetCLICode() }
                            theme="dark"
                        />
                    </div>

                    <div className="mt-3">
                        <Text>
                            Check out the <a
                            href={ SDKMeta.dotNet.readme }
                            target="_blank"
                            rel="noopener noreferrer"
                            className="link external"
                        >
                            <Icon name="github" />documentation
                        </a> to learn more about other installation options.
                        </Text>
                    </div>
                </>
            );
        }

        return null;
    };

    const generateInitialisationStepTitle = (technology: SupportedTraditionalOIDCAppTechnologyTypes): ReactNode => {

        if (technology === SupportedTraditionalOIDCAppTechnologyTypes.TOMCAT_OIDC_AGENT) {
            return "Configure";
        }

        if (technology === SupportedTraditionalOIDCAppTechnologyTypes.DOT_NET) {
            return "Configure";
        }

        return "Configure";
    };

    const generateInitialisationStep = (technology: SupportedTraditionalOIDCAppTechnologyTypes): ReactNode => {

        if (technology === SupportedTraditionalOIDCAppTechnologyTypes.TOMCAT_OIDC_AGENT) {

            return (
                <>
                    {
                        !callbacksUpdated
                            && !isEmpty(sampleServerHost)
                            && !(checkCallbacks(
                                sampleServerHost + SDKMeta.tomcatOIDCAgent.sample.sigInRedirectURL))
                            ? (
                                <Message warning>
                                    <p>
                                        In order to try out the sample, you need to
                                        add <strong>
                                        { sampleServerHost + SDKMeta.tomcatOIDCAgent.sample.sigInRedirectURL }
                                        </strong> to <strong>Authorized redirect URIs</strong>
                                        <Button
                                            color="orange"
                                            floated="right"
                                            onClick={
                                                () => handleAddCallback(sampleServerHost +
                                                    SDKMeta.tomcatOIDCAgent.sample.sigInRedirectURL)
                                            }
                                        >
                                            Add Now
                                        </Button>
                                    </p>
                                </Message>
                            )
                            : null
                    }

                    <Text>
                        We&apos;re providing { config.ui.productName } endpoints to the application using a property file, which is read by the
                        Asgardeo OIDC Agent.
                    </Text>
                    <Text>
                        Create a file named <code className="inline-code">oidc-sample-app.properties</code> inside <code
                        className="inline-code">YOUR_APP/src/main/resources</code> directory,
                        using the content below.
                    </Text>

                    <div className="code-segment">
                        <CodeEditor
                            readOnly
                            showLineNumbers
                            withClipboardCopy
                            language="htmlmixed"
                            sourceCode={ tomcatOIDCAgentSamplePropertiesCode(SDKInitConfig) }
                            options={ {
                                lineWrapping: true
                            } }
                            height="100%"
                            theme="dark"
                        />
                    </div>

                    <Divider hidden/>

                    <Text>
                        A comprehensive list of the properties used above, can be found in the <a
                            href={ SDKMeta.tomcatSAMLAgent.catalog }
                            target="_blank"
                            rel="noopener noreferrer"
                            className="link external"
                        >Configuration Catalog</a>.
                    </Text>

                    <Divider hidden/>

                    <Text>
                        Copy and paste the following configurations to <code
                        className="inline-code">YOUR_APP/src/main/webapp/WEB-INF/web.xml</code> file.
                    </Text>

                    <div className="code-segment">
                        <CodeEditor
                            readOnly
                            showLineNumbers
                            withClipboardCopy
                            language="htmlmixed"
                            sourceCode={ tomcatOIDCAgentSampleWebXMLCode() }
                            options={ {
                                lineWrapping: true
                            } }
                            theme="dark"
                        />
                    </div>
                </>
            );
        }

        if (technology === SupportedTraditionalOIDCAppTechnologyTypes.DOT_NET) {

            return (
                <>
                    <Text>
                        Once you have installed the SDK, create a file named <code className="inline-code">
                        App.config</code> in the application path and add the following configuration.
                    </Text>

                    <div className="code-segment">
                        <CodeEditor
                            readOnly
                            showLineNumbers
                            withClipboardCopy
                            language="htmlmixed"
                            sourceCode={ dotNetSDKConfigCode(SDKInitConfig) }
                            options={ {
                                lineWrapping: true
                            } }
                            height="100%"
                            theme="dark"
                        />
                    </div>
                </>
            );
        }

        return null;
    };

    const generateAuthenticationStep = (technology: SupportedTraditionalOIDCAppTechnologyTypes): ReactNode => {

        if (technology === SupportedTraditionalOIDCAppTechnologyTypes.TOMCAT_OIDC_AGENT) {

            return (
                <>
                    <Text>
                        In the <code className="inline-code">index.html</code>, add a login button which we would use to
                        forward the user to the secured page.
                    </Text>

                    <div className="code-segment">
                        <CodeEditor
                            beautify
                            readOnly
                            showLineNumbers
                            withClipboardCopy
                            language="htmlmixed"
                            sourceCode={ tomcatOIDCAgentLoginButtonCode() }
                            options={ {
                                lineWrapping: true
                            } }
                            height="100%"
                            theme="dark"
                        />
                    </div>

                    <Divider hidden/>

                    <Text>
                        Add the following snippet to enable logout from the secured page.
                    </Text>

                    <div className="code-segment">
                        <CodeEditor
                            readOnly
                            oneLiner
                            withClipboardCopy
                            language="htmlmixed"
                            sourceCode={ tomcatOIDCAgentLogoutCode() }
                            theme="dark"
                        />
                    </div>
                </>
            );
        }

        if (technology === SupportedTraditionalOIDCAppTechnologyTypes.DOT_NET) {

            return (
                <>
                    <Text>
                        Use the following code snippet to authenticate a user.
                    </Text>

                    <div className="code-segment">
                        <CodeEditor
                            readOnly
                            showLineNumbers
                            withClipboardCopy
                            language="htmlmixed"
                            sourceCode={ dotNetSDKLoginCode() }
                            options={ {
                                lineWrapping: true
                            } }
                            height="100%"
                            theme="dark"
                        />
                    </div>

                    <Divider hidden/>

                    <Text>
                        Use the following code snippet to log out an already logged in user.
                    </Text>

                    <div className="code-segment">
                        <CodeEditor
                            readOnly
                            oneLiner
                            withClipboardCopy
                            language="htmlmixed"
                            sourceCode={ dotNetSDKLogoutCode() }
                            theme="dark"
                        />
                    </div>
                </>
            );
        }

        return null;
    };

    const integrationFlowSteps: VerticalStepperStepInterface[] = [
        {
            stepContent: generateConfigureStep(technology),
            stepTitle: generateConfigureStepTitle(technology)
        },
        {
            stepContent: generateInitialisationStep(technology),
            stepTitle: generateInitialisationStepTitle(technology)
        },
        {
            stepContent: generateAuthenticationStep(technology),
            stepTitle: "Add Login"
        }
    ];

    const renderPrerequisitesStep = (technology: SupportedTraditionalOIDCAppTechnologyTypes): ReactElement => {

        if (!(technology === SupportedTraditionalOIDCAppTechnologyTypes.TOMCAT_OIDC_AGENT
            || technology === SupportedTraditionalOIDCAppTechnologyTypes.DOT_NET)) {

            return null;
        }

        const generateContent = () => {

            if (technology === SupportedTraditionalOIDCAppTechnologyTypes.TOMCAT_OIDC_AGENT) {
                return (
                    <>
                        <Text>
                            In this section we&apos;re guiding you on configuring your own Java application that
                            uses <strong>Apache Maven</strong> (3.6.x or higher) as the package manager
                            and <strong>Apache Tomcat</strong> as the deployment engine.
                        </Text>
                        <Text>To download the latest <strong>Apache Maven</strong>, navigate to the official <a
                            href="https://maven.apache.org/download.cgi"
                            target="_blank"
                            rel="noopener noreferrer"
                            className="link external"
                        >downloads</a> page.
                        </Text>
                    </>
                );
            }

            if (technology === SupportedTraditionalOIDCAppTechnologyTypes.DOT_NET) {
                return (
                    <>
                        <Text>
                            <strong>Microsoft Windows 8</strong> (Or server equivalent) or greater.
                        </Text>
                        <Text>
                            You will need to have <strong>.NET Framework 4.6.1 or greater </strong>
                            installed on your environment to try out the integration. To download
                            <strong>.NET Framework</strong>, navigate to the official <a
                                href="https://dotnet.microsoft.com/download/dotnet-framework/net461"
                                target="_blank"
                                rel="noopener noreferrer"
                                className="link external"
                            >downloads</a> page.
                        </Text>
                    </>
                );
            }
        };

        return (
            <div className="mt-3 mb-6">
                <Heading as="h3">Prerequisite</Heading>
                { generateContent() }
            </div>
        );
    };

    return (
        <>
            { renderPrerequisitesStep(technology) }
            <VerticalStepper
                alwaysOpen
                isSidePanelOpen
                stepContent={ integrationFlowSteps }
                isNextEnabled={ technology !== undefined }
                data-testid={ `${ testId }-vertical-stepper` }
            />
        </>
    );
};
