/**
 * 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 { TestableComponentInterface } from "@wso2is/core/models";
import { EncodeDecodeUtils } from "@wso2is/core/utils";
import { CodeEditor, Heading, Text } from "@wso2is/react-components";
import React, { FunctionComponent, ReactElement, ReactNode, useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { Divider, DropdownItemProps, Icon, List } from "semantic-ui-react";
import {
    dotNetSDKConfigCode,
    dotNetSDKLoginCode,
    dotNetSDKLogoutCode,
    dotNetSDKNugetCLICode,
    tomcatOIDCAgentLoginButtonCode,
    tomcatOIDCAgentLogoutCode,
    tomcatOIDCAgentMavenDependencyCode,
    tomcatOIDCAgentSamplePropertiesCode,
    tomcatOIDCAgentSampleWebXMLCode,
    tomcatOIDCJKSSamplePropertiesCode
} from "./code-blocks";
import { SDKMeta } from "./meta";
import { SupportedTraditionalOIDCAppTechnologyTypes } from "./models";
import { ApplicationInterface, ApplicationTemplateInterface } 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 {
        inboundProtocolConfig,
        technology,
        [ "data-testid" ]: testId
    } = props;

    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>("");

    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 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>
                        Starting with the <code className="inline-code">pom.xml</code>, the following dependencies
                        should be added for the webApp to be using the OIDC SDK.
                    </Text>

                    <div className="code-segment">
                        <CodeEditor
                            readOnly
                            showLineNumbers
                            withClipboardCopy
                            height="100%"
                            language="htmlmixed"
                            sourceCode={ tomcatOIDCAgentMavenDependencyCode() }
                            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 (
                <>
                    <Text>
                        Before the <code className="inline-code">web.xml</code> configurations, we will look at adding
                        the resources files. In the <code className="inline-code">oidc-sample-app</code>, create a file
                        named <code className="inline-code">oidc-sample-app.properties</code> in the <code
                        className="inline-code">src/main/resources</code> directory. The <code
                        className="inline-code">oidc-sample-app.properties</code> file contains properties similar to
                        the following.
                    </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 can be found in the <a
                        href={ SDKMeta.tomcatSAMLAgent.catalog }
                        target="_blank"
                        rel="noopener noreferrer"
                        className="link external"
                        >Configuration Catalog</a>.
                        These properties are required for the OIDC SDK to communicate with the <strong>
                        { config.ui.productName }</strong>.
                    </Text>

                    <Divider hidden/>

                    <Text>
                        Next, we need to find and set JKS properties required for IS server communication. For that,
                        create a file named <code className="inline-code">jks.properties</code> in the <code
                        className="inline-code">src/main/resources</code> directory. The content of the jks.properties
                        file should be similar to.
                    </Text>

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

                    <Divider hidden/>

                    <Text>
                        Finally, copy and paste the following configurations to the <code
                        className="inline-code">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>
                            You will need to have <strong>Apache Maven 3.6.x or higher</strong> installed on
                            your environment to try out the integration.
                        </Text>
                        <Text>To download <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` }
            />
        </>
    );
};
