import * as React  from "react";
import { ListView } from '../../../../Controls/ListView';
import { CommandsBar } from '../../../../Controls/CommandsBar';
import {FormDesigner } from '../../../../Controls/FormDesigner';
import { Toolbar } from '../../../../Controls/Toolbar';
import {EntityService,CachingService, WorkflowService} from '../../../../Services';
import { Field, Entity } from "../../../../Models";
import { Redirect } from "react-router-dom";
import { Breadcrumb, PrimaryButton, DefaultButton} from 'office-ui-fabric-react/lib';
import { Modal } from 'office-ui-fabric-react/lib/Modal';
import { DateUtils } from "../../../../Utils";
import { WorkflowVersion, StoredTypeDefinition, EntityWorkflow, StoredTypeField } from "../../../../Models/WorkflowManager";
import {
    IColumn
} from 'office-ui-fabric-react/lib/DetailsList';

export class EntityDesigner extends React.Component<any,any> {
    private _entityService : EntityService = new EntityService();
    private _cachingService : CachingService = new CachingService();
    private _workflowService: WorkflowService = new WorkflowService();
    private _dateUtils:DateUtils = new DateUtils();

    constructor(props: any) {
        super(props);
        let entity:Entity = this._cachingService.read('tempEntity') as Entity;
        this.state = {
            elements: entity.fields,
            goBack: false,
            workspaceId:0,
            showModal:false,
            selectedVersion:{},
            redirectToVersionDetails:false,
            versions:new Array<WorkflowVersion>(),
            versionsColumns: this.getVersionsColumns(),
            showVersionsModal:false,
            selectedWorkflow : new EntityWorkflow()
        }
    }

    _deleteElement = (index: number) => {
        if ( this.state.elements[index]) {
            this.state.elements.splice(index, 1)
            this._updateAllIndexes();
        }
        this.setState({ elements:  this.state.elements });
    };

    _updateAllIndexes = () => {
        for (var i = 0; i <  this.state.elements.length; i++) {
            this.state.elements[i].index = i;
        }
    }

    _moveElementToNewIndex = (elementIndex: number, newIndex: number) => {
        if ( this.state.elements[newIndex] &&  this.state.elements[elementIndex]) {
            var temp =  this.state.elements.splice(elementIndex, 1);
            this._updateAllIndexes();
            this.state.elements.splice(newIndex, 0, temp[0]);
            this._updateAllIndexes();
        }
        this.setState({ elements:  this.state.elements });
    };

    // _updateProperty = (displayName : string, index : number) => {
    //     if (this.state.elements[index]) {
    //         this.state.elements[index].displayName = displayName
    //         this.state.elements[index].name = displayName
    //     }
    //     this.setState({ elements: this.state.elements });

    // }

    _addData = (item: Field, index: number) => {

        item.index = this.state.elements.length;

        this.state.elements.push(item);

        this.setState({ elements: this.state.elements });
    };

    saveForm(manageWorkflow:boolean) {
        let entity:Entity = this._cachingService.read('tempEntity') as Entity;
        entity.fields = this.state.elements;
        this._entityService.saveEntity(entity).then(
            result=>{
                this.setState({workspaceId:entity.workspaceId});

                if(manageWorkflow){
                    this.manageVersions(result.name,result.displayName);
                }
                else
                {
                    this.setState({goBack:true});
                }
            },
            error=>{
                alert(error);
            }
        );
    }

    cancelForm() {
        let entity:Entity = this._cachingService.read('tempEntity') as Entity;

        this.setState({goBack:true,workspaceId:entity.workspaceId});
    }

    private _workFlowModal = (): void => {
        this.setState({ showModal: true });
    };

    private _closeModal = (): void => {
        this.setState({ showModal: false });
    };



    


//////////////////////// start versions //////////////////

private getVersionsColumns() {
    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>);
        }
    })

    return columns;
}
    private getNewStoredTypeDefinition(fqn:string){
        let definition = new StoredTypeDefinition();
        definition.DefinitionType=6;
        definition.FQN = fqn;

        definition.Fields = new Array<StoredTypeField>();
        let field = new StoredTypeField();
        field.DataType=2;
        field.FieldName = "Id";
        field.PrimaryKeyField = true;
        definition.Fields.push(field);

        return definition;
    }
    private getNewEntityWorkflow(definition:StoredTypeDefinition,entityDisplayName:string){
        let workflow =  new EntityWorkflow();
        workflow.EntityTypeId = definition.Id;
        workflow.Name = entityDisplayName + " Workflow";
    
        return workflow;
    }
    private manageVersions(fqn:string,entityDisplayName:string){
        this.setState({ versions: [] })
        this._workflowService.getWorkflowByFQN(fqn).then(workflow=>{
            if(workflow == null){                
                this._workflowService.defineType(this.getNewStoredTypeDefinition(fqn)).then(definition => {
                    this._workflowService.createEntityWorkflow(this.getNewEntityWorkflow(definition,entityDisplayName)).then(newWorkflow => {
                        this.setState({selectedWorkflow:newWorkflow});

                        this._workflowService.getWorkflowVesrions(newWorkflow.Id).then(workflowVersions => {
                            this.setState({ versions: workflowVersions })
                        }, error => {
                            console.log(error);
                            alert(error);
                        });
                    }, error => {
                        console.log(error);
                        alert(error);
                    });
                }, error => {
                    console.log(error);
                    alert(error);
                });
            }
            else{
                this.setState({ selectedWorkflow:workflow, versions: workflow.Versions })
            }
        }, error => {
            console.log(error);
            alert(error);
        });

        this.setState({ showVersionsModal: true })
    };


    private selectedVersionChanged(version:any){
        if(!version)
            return;
            
        this.setState({selectedVersion : version});
        this.setState({redirectToVersionDetails:true});
    }

    private _closeVersionsModal = (): void => {
        this.setState({ showVersionsModal: false });
    };

//////////////////////// end versions //////////////////


    public render() {
        return (
            
this.state.redirectToVersionDetails?<Redirect to={"/workflowDesigner/" + this.state.selectedWorkflow.Id + "/" + this.state.selectedVersion.Id} push></Redirect>:
            this.state.goBack?<Redirect to={"/entityList/"+this.state.workspaceId}></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" >
                
                <CommandsBar Commands={[{
                    key: "save",
                    name: "Save",
                    icon: "Save",
                    onClick: this._workFlowModal.bind(this)
                    },
                    {
                        key: "cancel",
                        name: "Cancel",
                        icon: "Cancel",
                        onClick: this.cancelForm.bind(this)
                    }]} />
                <Toolbar callbackFromParent={this._addData} />
                <FormDesigner
                    moveElementToNewIndex={this._moveElementToNewIndex}
                    // updateProperty={this._updateProperty}
                    deleteElementcallback={this._deleteElement}
                    formElements={this.state.elements} />
                    <Modal
                    isOpen={this.state.showModal}
                    onDismiss={this._closeModal}
                    isBlocking={false}
                    containerClassName="ms-modalExample-container"
                    >

                    <div className="ms-modalExample-body">
                        <h3>Do you want to create workflow ?</h3>

                    </div>

                    <div className="ms-modalExample-footer modalFooter" >
                        <PrimaryButton style={{ marginRight: '8px' }} onClick={() => { this._closeModal(); this.saveForm(true);}} >
                            Yes
                        </PrimaryButton>
                        <DefaultButton onClick={() => { this.saveForm(false); this._closeModal(); }}>No</DefaultButton>
                    </div>
                    </Modal>
                    <Modal
                    isOpen={this.state.showVersionsModal}
                    onDismiss={this._closeVersionsModal}
                    isBlocking={true}
                    containerClassName="ms-modalExample-container" forceFocusInsideTrap={true}>

                    <div className="ms-modalExample-header">
                        <span>Versions</span>
                    </div>
                    <div className="ms-modalExample-body">
                    <ListView
                            SelectedItemChanged={this.selectedVersionChanged.bind(this)}
                            Items={this.state.versions}
                            Columns={this.state.versionsColumns} />
                    </div>

                    <div className="ms-modalExample-footer modalFooter" >
                        <PrimaryButton style={{ marginRight: '8px' }} href={"/workflowDesigner/" + this.state.selectedWorkflow.Id + "/0"}>
                            New
                        </PrimaryButton>
                        <DefaultButton onClick={this._closeVersionsModal}>Cancel</DefaultButton>
                    </div>
                </Modal>
                </div>
            </div>
        )
    }
} 