import * as React from 'react';
import { TextField } from 'office-ui-fabric-react/lib/TextField';
import { Modal } from 'office-ui-fabric-react/lib/Modal';
import { EntityService, CachingService } from '../../../../Services';
import {
    IColumn
} from 'office-ui-fabric-react/lib/DetailsList';
import { Breadcrumb, DefaultButton, PrimaryButton, Dropdown } from 'office-ui-fabric-react/lib';
import { Entity, Field } from '../../../../Models';
import { RouteComponentProps } from 'react-router';
import { Command } from "../../../../Models"
import { ListView } from '../../../../Controls/ListView';
import { CommandsBar } from '../../../../Controls/CommandsBar';
import './EntityList.css'
import { EntityCreationMode } from 'src/Enums';
let _items: Entity[] = [];

export interface IData {
    columns: IColumn[];
    items: Entity[];
}

export class EntityList extends React.Component<{} & RouteComponentProps<{ id: number }>, any>
{
    private _entityService: EntityService = new EntityService();
    private _cachingService: CachingService = new CachingService();
    constructor(props: {} & RouteComponentProps<{ id: number }>) {
        super(props);
        this.state = {
            workspaceId: this.props.match.params.id,
            items: _items,
            columns: new Array<IColumn>(),
            showModal: false,
            selectedItem: { workspaceId: this.props.match.params.id },
            commands: new Array<Command>(),
            creationModes:[
                {key:EntityCreationMode.Normal,name:"Normal"},
                {key:EntityCreationMode.Wizard,name:"Wizard"}
            ]
        };
        this.loadColumns();
        this.loadEntities(this.props.match.params.id);
    }
    private _handlecreationModeChange(value: any){
        this.state.selectedItem.creationMode = value.key;
        this.setState({selectedItem:this.state.selectedItem});
    }
    private loadColumns(){
        this.state.columns.push({
            dataType: 'string',
            name: 'Name',
            fieldName: 'displayName',
            minWidth: 180,
            maxWidth: 350            
        },{
            dataType: 'string',
            name: 'Description',
            fieldName: 'description',
            minWidth: 300,
            maxWidth: 500
        })
    }
    private getCommonCommands(): Command[] {
        let commands = new Array<Command>();
        commands.push(
            {
                key: "addEntity",
                name: "Create Entity",
                icon: "Add",
                onClick: this.addEntity.bind(this)
            });
        return commands;
    }
    private getEntityCommands(): Command[] {
        let commands = this.getCommonCommands();
        commands.push(
            {
                key: "removeEntity",
                name: "Remove",
                icon: "Remove",
                onClick: this.deleteEntity.bind(this)
            },
            {
                key: "edit",
                name: "Edit",
                icon: "Edit",
                onClick: this.editEntity.bind(this)
            });

        return commands;
    }

    private selectedEntityChanged(entity: Entity) {
        if (!entity)
            return;

        this.setState({ selectedItem: entity });

        this.setState({ commands: this.getEntityCommands() });
    }
    public render(): JSX.Element {
        return (
            <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
                            selectionModeType={true}
                            Items={this.state.items}
                            SelectedItemChanged={this.selectedEntityChanged.bind(this)}
                            Columns={this.state.columns} />
                    </div>
                </div>


                <Modal
                    isOpen={this.state.showModal}
                    onDismiss={this._closeModal}
                    isBlocking={false}
                    containerClassName="ms-modalExample-container">

                    <div className="ms-modalExample-header">
                        <span>Add new entity</span>
                    </div>
                    <div className="ms-modalExample-body">
                        <p>Please enter Entity title, once you click add you can proceed to add Field to your new entity</p>
                        <div>
                            <TextField label="Entity title" placeholder="Entity title" value={this.state.selectedItem.displayName} onChanged={this._handletitleChange.bind(this)} />
                        </div>
                        <div>
                            <Dropdown
                                label="Creation Mode"
                                defaultSelectedKey={this.state.selectedItem.creationMode}
                                options={this.state.creationModes && this.state.creationModes.length>0?this.state.creationModes.map((creationMode: any) => { 
                                    return { key: creationMode.key, text: creationMode.name } }):""}
                                onChanged={this._handlecreationModeChange.bind(this)}
                            />
                        </div>
                        <div>
                            <TextField label="Description" placeholder="Description" multiline rows={6} value={this.state.selectedItem.description} onChanged={this._handledescriptionChange.bind(this)} />
                        </div>
                    </div>

                    <div className="ms-modalExample-footer modalFooter" >
                        <PrimaryButton style={{ marginRight: '8px' }} href="/entityDesigner" onClick={(e) => this.next()} >
                            Next
                        </PrimaryButton>
                        <DefaultButton onClick={this._closeModal}>Cancel</DefaultButton>
                    </div>
                </Modal>

            </div>
        );
    }
    _handletitleChange(value: any) {
        this.state.selectedItem.name = value;
        this.state.selectedItem.displayName = value;
    };

    _handledescriptionChange(value: any) {
        this.state.selectedItem.description = value;
    };

    private addEntity() {
        let newEntity = new Entity();
        newEntity.workspaceId = this.state.workspaceId;
        newEntity.fields = [];
        let nameField = new Field();
        nameField.name = "Name";
        nameField.displayName = "Name";
        nameField.isUnique = true;
        nameField.allowNull = false;
        nameField.isSystemDefined = true;
        nameField.showInListView = true;
        newEntity.fields.push(nameField);
        this.setState({ selectedItem: newEntity, showModal: true });
    };

    private editEntity() {
        if (this.state.selectedItem) {
            this.setState({ showModal: true });
        }
    }

    private deleteEntity() {
        if (this.state.selectedItem) {
            this._entityService.deleteEntity(this.state.selectedItem.id)
                .then(result => {
                    this._entityService.listEntities(this.state.selectedItem.workspaceId).then(listResult => {
                        this.setState({ items: listResult });
                    });
                    alert("Deleted successfully");
                }, error => {
                    alert(error);
                });
        }
    }

    loadEntities = (workspaceId: number) => {
        this._entityService.listEntities(workspaceId).then(result => {
            this.setState({ items: result })
            this.setState({ commands: this.getCommonCommands() });
        }, error => {
            alert(error);
        });
    }

    private next() {
        this._cachingService.store('tempEntity', this.state.selectedItem);
    }


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