import * as React from 'react';
import { TextField } from 'office-ui-fabric-react/lib/TextField';
import { Dropdown } from 'office-ui-fabric-react/lib/components/Dropdown';

import { WorkflowDesignerService } from '../../../../Services';
import {
    IColumn
} from 'office-ui-fabric-react/lib/DetailsList';
import { Breadcrumb, DefaultButton, PrimaryButton, Panel, PanelType } from 'office-ui-fabric-react/lib';
import { Command } from "../../../../Models"
import { ListView } from "../../../../Controls/ListView"
import { CommandsBar } from "../../../../Controls/CommandsBar"
import { Workflow, WorkflowVersion, EntityField } from '../../../../Models/WorkflowDesigner';
import { Redirect } from 'react-router-dom';
import { DateUtils } from '../../../../Utils';
import { WorkflowFieldTypes } from '../../../../Enums';


export default class WorkflowManager extends React.Component<any, any>
{
    private _workflowDesignerService: WorkflowDesignerService = new WorkflowDesignerService();
    private _dateUtils: DateUtils = new DateUtils();
    private _fieldTypes = [{
        Id : WorkflowFieldTypes.String,
        DisplayName:"String"    
    },
    {
        Id : WorkflowFieldTypes.Integer,
        DisplayName:"Integer"    
    },
    {
        Id : WorkflowFieldTypes.Float,
        DisplayName:"Float"    
    },
    {
        Id : WorkflowFieldTypes.Double,
        DisplayName:"Double"    
    },
    {
        Id : WorkflowFieldTypes.Date,
        DisplayName:"Date"    
    },
    {
        Id : WorkflowFieldTypes.Boolean,
        DisplayName:"Boolean"    
    },
    {
        Id : WorkflowFieldTypes.JsonString,
        DisplayName:"Json String"    
    }
    ]

    constructor(props: any) {
        super(props);
        this.state = {
            workflows: new Array<Workflow>(),
            columns: new Array<IColumn>(),
            showVersionsPanel: false,
            showWorkflowPanel: false,
            selectedWorkflow: new Workflow(),
            commands: new Array<Command>(),
            versions: new Array<WorkflowVersion>(),
            versionsColumns: new Array<IColumn>(),
            selectedVersion: {},
            redirectToDetails: false,
        };
        this.loadColumns();
        this.loadWorkflows();
    }
    private loadColumns() {
        this.state.columns.push({
            dataType: 'string',
            name: 'Name',
            fieldName: 'Name',
            minWidth: 210,
            maxWidth: 350
        }, {
                dataType: 'string',
                name: 'Entity',
                fieldName: 'EntityName',
                minWidth: 210,
                maxWidth: 350
            })
    }

    private loadVersionsColumns() {
        let columns = []
        columns.push({
            dataType: 'number',
            name: 'Version Number',
            fieldName: 'VersionNumber',
            minWidth: 100,
            maxWidth: 350,
            onRender: (item?: any, index?: number, column?: IColumn) => {
                return (
                    item.IsDraft ?
                        <div style={{ color: "red" }}>{item.VersionNumber}</div> : <div style={{ color: "blue" }}>{item.VersionNumber}</div>);
            }
        }, {
                dataType: 'string',
                name: 'CreatedOn',
                fieldName: 'CreatedOn',
                minWidth: 210,
                maxWidth: 350,
                onRender: (item?: any, index?: number, column?: IColumn) => {
                    return (
                        <div>{this._dateUtils.formatDateTime(item.CreatedOn)
                        }</div>);
                }
            })
        this.setState({ versionsColumns: columns });
    }
    private addWorkflow() {
        let newWorkflow = new Workflow();
        this.setState({ selectedWorkflow: newWorkflow, showWorkflowPanel: true });
    }
    private editWorkflow() {
        this.setState({ showWorkflowPanel: true })

    };
    private manageVersions() {
        this.setState({ versions: [] })
        this._workflowDesignerService.getWorkflowVersions(this.state.selectedWorkflow.Id).then(result => {
            this.loadVersionsColumns();
            this.setState({ versions: result })
        }, error => {
            console.log(error);
            alert(error);
        });
        this.setState({ showVersionsPanel: true });
    };

    private getCommonCommands(): Command[] {
        let commands = new Array<Command>();
        commands.push(
            {
                key: "addWorkflow",
                name: "New",
                icon: "Add",
                onClick: this.addWorkflow.bind(this)
            });
        return commands;
    }
    private getWorkflowCommands(): Command[] {
        let commands = this.getCommonCommands();
        commands.push(
            {
                key: "editWorkflow",
                name: "Edit",
                icon: "Workflow",
                onClick: this.editWorkflow.bind(this)
            },
            {
                key: "versions",
                name: "Versions",
                icon: "versions",
                onClick: this.manageVersions.bind(this)
            }
        );

        return commands;
    }

    private selectedWorkflowChanged(workflow: Workflow) {
        //debugger;
        if (!workflow)
            return;

        this.setState({ selectedWorkflow: workflow });

        this.setState({ commands: this.getWorkflowCommands() });
    }

    private closeVersionsPanel() {
        return (): void => {
            this.setState({ showVersionsPanel: false });
        }
    } 
    private closeWorkflowPanel() {
        return (): void => {
            this.setState({ showWorkflowPanel: false });
        }
    }
    _handleEntityNameChange(value: any) {
        this.state.selectedWorkflow.EntityName = value;
    };
    _handleIdFieldNameChange(value: any) {
        if(this.state.selectedWorkflow.PrimaryKeyField==null)
            this.state.selectedWorkflow.PrimaryKeyField = new EntityField();

        this.state.selectedWorkflow.PrimaryKeyField.FieldName = value;
    };
    _handleIdFieldTypeChange(value: any) {
        if(this.state.selectedWorkflow.PrimaryKeyField==null)
            this.state.selectedWorkflow.PrimaryKeyField = new EntityField();

        this.state.selectedWorkflow.PrimaryKeyField.Type = value.key;
    };
    _handleWorkflowTitleChange(value: any) {
        this.state.selectedWorkflow.Name = value;
    };
    public render(): JSX.Element {
        return (
            this.state.redirectToDetails ? <Redirect to={"/workflowDesigner/" + this.state.selectedWorkflow.Id + "/" + this.state.selectedVersion.Id} push></Redirect>
                :
                <div>
                    <div className="ms-Grid-row breadcrumb-Border">
                        <div className="ms-Grid-col ms-lg12">
                            <div className="breadcrumb">
                                <Breadcrumb
                                    items={[
                                        { text: 'Workspaces', key: 'Workspace', href: "/workspace" },

                                    ]}
                                    ariaLabel={'Website breadcrumb'}
                                />
                            </div>
                        </div>
                    </div>

                    <div className="ms-Grid-row" >
                        <div>
                            <CommandsBar Commands={this.state.commands} />
                        </div>
                        <div className="ms-Grid-col ms-lg12" >
                            <ListView
                                Items={this.state.workflows}
                                SelectedItemChanged={this.selectedWorkflowChanged.bind(this)}
                                Columns={this.state.columns} />
                        </div>
                    </div>
                    <Panel
                        className="panelStyle"
                        isOpen={this.state.showVersionsPanel}
                        onDismiss={this.closeVersionsPanel()}
                        type={PanelType.medium}
                        headerText="Versions"
                        isLightDismiss={true}
                        onRenderFooter={this._showVersionButtons}

                    >
                        <ListView
                            selectionModeType={true}
                            SelectedItemChanged={this.selectedVersionChanged.bind(this)}
                            Items={this.state.versions}
                            Columns={this.state.versionsColumns} />
                    </Panel>
                    <Panel
                        className="panelStyle"
                        isOpen={this.state.showWorkflowPanel}
                        onDismiss={this.closeWorkflowPanel()}
                        type={PanelType.medium}
                        headerText="Workflow"
                        isLightDismiss={true}
                        onRenderFooter={this._showWorkflowButton}
                    >
                        <div className="ms-Grid-row">
                            <div className="ms-Grid-col ms-lg6"> <TextField value={this.state.selectedWorkflow.Name} onChanged={this._handleWorkflowTitleChange.bind(this)} label="Workflow Title" /></div>
                            <div className="ms-Grid-col ms-lg6"><TextField value={this.state.selectedWorkflow.EntityName} onChanged={this._handleEntityNameChange.bind(this)} label="Entity Name" /></div>
                        </div>

                        <div className="ms-Grid-row">
                        <h3>Id Field</h3>
                            <div className="ms-Grid-col ms-lg6"> 
                            <TextField value={this.state.selectedWorkflow.PrimaryKeyField !=null?this.state.selectedWorkflow.PrimaryKeyField.FieldName:""} onChanged={this._handleIdFieldNameChange.bind(this)} label="Name" />
                            </div>
                            <div className="ms-Grid-col ms-lg6">
                            <Dropdown
                            label="Type"
                            defaultSelectedKey={this.state.selectedWorkflow.PrimaryKeyField !=null?this.state.selectedWorkflow.PrimaryKeyField.Type:""}
                            options={this._fieldTypes.map((fieldType: any) => { return { key: fieldType.Id, text: fieldType.DisplayName } })}
                            onChanged={this._handleIdFieldTypeChange.bind(this)}
  
                            />
                            </div>
                                                
                            
                        </div>
                    </Panel>
                </div>
        );
    }

    private _showVersionButtons = (): JSX.Element => {
        return (
            <div className="ms-modalExample-footer modalFooter" >
                <PrimaryButton style={{ marginRight: '8px' }} href={"/workflowDesigner/" + this.state.selectedWorkflow.Id + "/0"}>
                    Clone
            </PrimaryButton>
            <PrimaryButton style={{ marginRight: '8px' }} href={"/workflowDesigner/" + this.state.selectedWorkflow.Id + "/0"}>
                    View
            </PrimaryButton>
                <PrimaryButton style={{ marginRight: '8px' }} href={"/workflowDesigner/" + this.state.selectedWorkflow.Id + "/0"}>
                    New
            </PrimaryButton>
                <PrimaryButton style={{ marginRight: '8px' }} href={"/workflowDesigner/" + this.state.selectedWorkflow.Id + "/0"}>
                    Edit
            </PrimaryButton>
                <DefaultButton onClick={this.closeVersionsPanel()}>Cancel</DefaultButton>
            </div>
        )
    }
    private _showWorkflowButton = (): JSX.Element => {
        return (
            <div className="ms-modalExample-footer modalFooter" >
                <PrimaryButton style={{ marginRight: '8px' }} onClick={(e) => this.saveWorkflow()}>
                    Save
            </PrimaryButton>
                <DefaultButton onClick={this.closeWorkflowPanel()}>Cancel</DefaultButton>
            </div>
        )
    }

    private selectedVersionChanged(version: any) {
        if (!version)
            return;

        this.setState({ selectedVersion: version });
        this.setState({ redirectToDetails: true });
    }

    private saveWorkflow() {
        this._workflowDesignerService.saveWorkflow(this.state.selectedWorkflow).then(result => {
            this.setState({ selectedWorkflow: result, showWorkflowPanel: false });
            this.loadWorkflows();
        }, error => {
            alert(error);
        });
    };

    loadWorkflows = () => {
        this._workflowDesignerService.listWorkflows().then(result => {
            this.setState({ workflows: result })
            this.setState({ commands: this.getCommonCommands() });
        }, error => {
            console.log(error);
            alert(error);
        });
    }



}