/**
 * 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, AlertLevels, AlertInterface } from "@wso2is/core/models";
import { CodeEditor, Heading, Text } from "@wso2is/react-components";
import React, { FunctionComponent, ReactElement, ReactNode, useState } from "react";
import { Button, Divider, Icon, Message } from "semantic-ui-react";
import {
    tomcatSAMLAgentDockerEnvCode,
    tomcatSAMLAgentDockerRunCode
} from "./code-blocks";
import { SDKMeta } from "./meta";
import { SupportedTraditionalSAMLAppTechnologyTypes } from "./models";
import {
    ApplicationInterface,
    ApplicationTemplateInterface,
    SAML2ConfigurationInterface,
    SupportedAuthProtocolTypes,
    updateAuthProtocolConfig
} from "../../../../features/applications";
import {
    VerticalStepper,
    VerticalStepperStepInterface
} from "../../../components/component-extensions/application/vertical-stepper";
import { useDispatch } from "react-redux";
import { addAlert } from "@wso2is/core/dist/src/store";

interface TryoutSamplesPropsInterface extends TestableComponentInterface {
    application: ApplicationInterface;
    template: ApplicationTemplateInterface;
    technology: SupportedTraditionalSAMLAppTechnologyTypes;
    inboundProtocolConfig: any;
}

const DOCKER_ENV_FILE_NAME = "sample-app.env";

const SAMPLE_ACS_URL = "http://localhost.com:8080/sample-app/home.jsp";

/**
 * Tryout Samples of Single Page Applications.
 *
 * @param {TryoutSamplesPropsInterface} props - Props injected into the component.
 * @return {React.ReactElement}
 */
export const TryoutSamples: FunctionComponent<TryoutSamplesPropsInterface> = (
    props: TryoutSamplesPropsInterface
): ReactElement => {

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

    const dispatch = useDispatch();

    const [ acsURLsUpdated, setACSURLsUpdated ] = useState<boolean>(false);

    const downloadEnvFile = (): void => {
        const blob = new Blob(
            [ tomcatSAMLAgentDockerEnvCode({
                certificate: inboundProtocolConfig.certificate,
                issuer: inboundProtocolConfig.issuer,
                samlIssuer: inboundProtocolConfig.saml.issuer,
                ssoUrl: inboundProtocolConfig.ssoUrl
            }) ],
            { type: "test/plain" }
        );
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.style.display = "none";
        a.href = url;
        a.download = DOCKER_ENV_FILE_NAME;
        document.body.appendChild(a);
        a.click();
        window.URL.revokeObjectURL(url);
    };

    const isACSURLAdded = (urlToCheck: string) => {
        const urlArray = inboundProtocolConfig.saml
            ? inboundProtocolConfig.saml.assertionConsumerUrls
            : [];

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

            return false;
        }

        return urlArray.includes(urlToCheck);
    };

    const handleAddCallback = (url: string) => {

        const acsURLs = inboundProtocolConfig.saml.assertionConsumerUrls;
        acsURLs.push(url);

        const body: SAML2ConfigurationInterface = {};

        body.manualConfiguration = {
            ...inboundProtocolConfig.saml,
            defaultAssertionConsumerUrl: url,
            assertionConsumerUrls: acsURLs
        };

        updateAuthProtocolConfig(application.id, body, SupportedAuthProtocolTypes.SAML)
            .then(() => {
                setACSURLsUpdated(true);
                dispatch(addAlert<AlertInterface>({
                    description: "Successfully updated the URLs in the application.",
                    level: AlertLevels.SUCCESS,
                    message: "Updated the URLs"
                }));
            })
            .catch(() => {
                dispatch(addAlert<AlertInterface>({
                    description: "An error occurred while updating the application.",
                    level: AlertLevels.ERROR,
                    message: "Error occurred"
                }));
            });
    };

    const generateConfigureStep = (technology: SupportedTraditionalSAMLAppTechnologyTypes) => {

        if (technology === SupportedTraditionalSAMLAppTechnologyTypes.JAVA_EE) {
            return (
                <>
                    {
                        !acsURLsUpdated
                        && (isACSURLAdded(SAMPLE_ACS_URL)
                            ? null
                            : (
                                <>
                                    <Message warning>
                                        <p>
                                            In order to try out the sample, you need to
                                            add <strong>{ SAMPLE_ACS_URL }</strong> to <strong>Assertion Consumer
                                            URIs</strong>
                                            <Button color="orange" floated="right"
                                                    onClick={ () => handleAddCallback(SAMPLE_ACS_URL) }>
                                                Add Now
                                            </Button>
                                        </p>
                                    </Message>
                                    <Divider hidden />
                                </>
                            )
                        )
                    }

                    <Text>
                        Download the <code className="inline-code">{ DOCKER_ENV_FILE_NAME }</code> file
                        to a preferred location.
                    </Text>

                    <Button
                        onClick={ downloadEnvFile }
                        className="download-config"
                        size='small'
                        primary
                        data-testid={ `${ testId }-download-config` }
                    >
                        Download Configuration File
                    </Button>

                    <Divider hidden/>

                    <Text>
                        or create a file named <code className="inline-code">
                        { DOCKER_ENV_FILE_NAME }</code> with the configuration below.
                    </Text>

                    <div className="code-segment" style={ {maxWidth: "1160px"} }>
                        <CodeEditor
                            readOnly
                            showLineNumbers
                            withClipboardCopy
                            height="100%"
                            language="htmlmixed"
                            sourceCode={ tomcatSAMLAgentDockerEnvCode({
                                certificate: inboundProtocolConfig.certificate,
                                issuer: inboundProtocolConfig.issuer,
                                samlIssuer: inboundProtocolConfig.saml.issuer,
                                ssoUrl: inboundProtocolConfig.ssoUrl
                            }) }
                            options={ {
                                lineWrapping: true
                            } }
                            theme="dark"
                        />
                    </div>

                    <Divider hidden/>

                    <Text>
                        This sample is configured to work in <strong> localhost.com</strong> domain. Therefore,
                        you need to append <code className="inline-code">127.0.0.1 localhost.com</code> to
                        <strong> /etc/hosts</strong> file of your machine.
                    </Text>
                </>
            );
        }

        return null;
    };

    const generateRunStep = (technology: SupportedTraditionalSAMLAppTechnologyTypes): ReactNode => {

        if (technology === SupportedTraditionalSAMLAppTechnologyTypes.JAVA_EE) {
            return (
                <>
                    <Text>
                        Run the following command in the location where you downloaded/created the <code
                        className="inline-code">{ DOCKER_ENV_FILE_NAME }</code> file from
                        the previous step and visit <a
                            href="http://localhost.com:8080/sample-app"
                            target="_blank"
                            rel="noopener noreferrer"
                            className="link external"
                            >http://localhost.com:8080/sample-app</a>
                    </Text>
                    <CodeEditor
                        oneLiner
                        readOnly
                        withClipboardCopy
                        language="htmlmixed"
                        sourceCode={ tomcatSAMLAgentDockerRunCode() }
                    />
                    <div className="mt-3">
                        For more guidance, navigate to our <a
                        href={ SDKMeta.tomcatSAMLAgent.readme }
                        target="_blank"
                        rel="noopener noreferrer"
                        className="link external"
                    >
                        <Icon name="github"/>Github repository
                    </a>
                    </div>
                </>
            );
        }

        return null;
    };

    const sampleFlowSteps: VerticalStepperStepInterface[] = [
        {
            stepContent: generateConfigureStep(technology),
            stepTitle: "Configure"
        },
        {
            stepContent: generateRunStep(technology),
            stepTitle: "Run"
        }
    ];

    const renderPrerequisitesStep = (): ReactElement => {

        return (
            <div className="mt-3 mb-6">
                <Heading as="h3">Prerequisite</Heading>
                <Text>
                    You will need to have <strong>Docker</strong> installed on
                    your environment to try out the sample.
                </Text>
                <Text>To setup <strong>Docker</strong>, navigate to the official <a
                        href="https://docs.docker.com/get-docker/"
                        target="_blank"
                        rel="noopener noreferrer"
                        className="link external"
                    >installation</a> page.
                </Text>
            </div>
        );
    };

    return (
        <>
            { renderPrerequisitesStep() }
            <VerticalStepper
                alwaysOpen
                isSidePanelOpen
                stepContent={ sampleFlowSteps }
                isNextEnabled={ technology !== undefined }
            />
        </>
    );
};
