import * as React from 'react';
import { MessageType } from '@theia/core';

import { Flex, Box } from '@rebass/grid';
import { PageHeader, Icon, Button} from 'antd';

import ConnectorVersionSelector from './connectors-version-selector';
import ConnectorStepper from './connectors-stepper';
import ConnectorFormRender from './connectors-form-render';
import { ContainerContext } from '../catalogo-context';

import { IConnectorConfig, IStepConnectorForm, IConnectorData } from '../../../common/catalogo-protocol';
import convertToBoolean from '../../../common/utils/converte-booleam-in-object';

var json = require('format-json');

interface ConnectorRendererProps {
    onBack: () => void;
    editingData: IConnectorData;
    connector: IConnectorConfig;
    steps: IStepConnectorForm[];

}

interface ConnectorRendererState {
    stepIndex: number;
    contextData: Object;
}

export default class ConnectorRenderer extends React.Component<ConnectorRendererProps, ConnectorRendererState> {
    static contextType = ContainerContext;
    context!: React.ContextType<typeof ContainerContext>;
    
    constructor(props) {
        super(props);

        this.state = {
            stepIndex: 0,
            contextData: {
                'step_0': {
                    version: null
                }
            }
        }
    }

    componentDidMount() {
        const { connector, editingData } = this.props;

        const version: string =
            editingData.version
                ? editingData.version
                : !Array.isArray(connector.version)
                    ? connector.version
                    : connector.version.length === 1
                        ? connector.version[0]
                        : null

        if(version) this._onSubmitedStep({version}, 0);
    }

    _onStep = (step: number) => this.setState({stepIndex: step});

    _onSubmitedStep = (data: any, nextStep: number) => {
        const { stepIndex } = this.state;
        this.setState({
            stepIndex: nextStep,
            contextData: {
                ...this.state.contextData,
                [`step_${stepIndex}`]: data
            }
        });
    }

    installConnnector = (data: any) => {
        const convertedData = convertToBoolean(data);
        this.context.resource.saveContents(json.plain(convertedData))
        .then(() => {
            this.context.service.logMessage({type: MessageType.Info, text: 'Connector has been installed.'});
            this.context.options.widget.close();
        })
        .catch(() => this.context.service.logMessage({type: MessageType.Error, text: 'Error on installing connector.'}));
    }

    uninstallConnector = () => {
        this.context.resource.saveContents('{}')
        .then(() => {
            this.context.service.logMessage({type: MessageType.Info, text: 'Connector has been uninstalled.'});
            this.props.onBack();
        })
        .catch(() => this.context.service.logMessage({type: MessageType.Error, text: 'Error on uninstalling connector.'}));
    }

    render() {
        const { connector, steps, editingData } = this.props;
        const { stepIndex, contextData } = this.state;

        return (
            <Flex flexDirection="column" width="100%">
                <PageHeader
                    backIcon={editingData.type ? false : <Icon type="arrow-left" />}
                    onBack={() => this.props.onBack()}
                    title={connector.title}
                    subTitle={connector.description}
                    ghost={false}
                    extra={editingData.type ? <Button type='primary' onClick={this.uninstallConnector}>Uninstall</Button> : null}
                />
                    {
                        contextData['step_0'].version
                            ? <Flex>
                                <Box width='70%'>
                                    <ConnectorFormRender
                                        stepForm={connector ? steps[stepIndex]: null}
                                        onSubmit={(data) => this._onSubmitedStep(data, stepIndex + 1)}
                                        context={contextData}
                                        onDone={(data) => this.installConnnector(data)}
                                    />
                                </Box>
                                <Box width='30%'>
                                    <ConnectorStepper step={stepIndex} steps={steps} onStep={(step) => this._onStep(step)}/>
                                </Box>
                            </Flex>
                            : <ConnectorVersionSelector
                                versions={[...connector.version]}
                                onVersionSelect={(value => this._onSubmitedStep(value, 0))}
                            />
                    }
            </Flex>
        );
    }
}
