import * as React from "react";
import { Panel, PanelType, IconButton, Dialog, DialogType, DialogFooter, DefaultButton } from "office-ui-fabric-react";
import { FormattedMessage } from "react-intl";
import { NewCommandBar } from "../../../Controls/NewCommandsBar";
import { RecordsListView } from "../../../Controls";
import { ListRecordsCriteria, FieldQuery, Sorting, Pagination, RecordField } from "../../../Models";
import { LoadingService } from "../../../Services/LoadingService";
import { RecordService, CachingService } from "../../../Services";
import { FieldsControl } from "../FieldsControl";
import { PrimaryButton as NewPrimaryButton } from "../PrimaryButton";

export class ManageSubjects extends React.Component<any, any> {
    private _pageSize = 10;
    private _entityId = 35;
    private _loadingService = new LoadingService();
    private _recordService: RecordService = new RecordService();
    private _cachingService = new CachingService();

    constructor(props: any) {
        super(props);

        let _criteria = new ListRecordsCriteria();
        _criteria.asLookup = false;
        _criteria.entityId = this._entityId;
        _criteria.query = new Array<FieldQuery>();
        let fieldQuery = new FieldQuery();
        fieldQuery.fieldId = 305;
        fieldQuery.value = this.props.meetingId;
        _criteria.query.push(fieldQuery);
        _criteria.pagination = new Pagination();
        _criteria.pagination.start = 0;
        _criteria.pagination.count = this._pageSize;

        this.state = {
            isListPanelVisible: false,
            totalRecords: 0,
            totalPages: 0,
            records: [],
            selectedRecord: {},
            emptyRecord: {},
            commands: this.getCommonCommands(),
            criteria: _criteria,
            isRecordDetailsVisibile: false,
            isRecordDeleteDialogVisibile: false,
        }



        this.loadRecords(_criteria);
        this._getRecord(0);
    }

    private getCommonCommands() {
        let commands = new Array<any>();
        commands.push(
            {
                key: "addRecord",
                name: "Create",
                icon: "Add",
                onClick: this.addRecord.bind(this)
            });

        return commands;
    }

    private getRecordCommands(record: any): any[] {
        let commands = this.getCommonCommands();

        if (record && record.id) {
            commands.push(
                {
                    key: "editRecord",
                    name: "Edit",
                    icon: "Edit",
                    onClick: this.editRecord.bind(this)
                });
            commands.push(
                {
                    key: "removeRecord",
                    name: "Delete",
                    icon: "Delete",
                    onClick: this.openDeleteRecordDialog.bind(this)
                });
        }

        return commands;
    }

    private selectedRecordChanged(entity: any) {
        if (!entity) return;

        this._getRecord(entity.id);
    }

    private _onRenderButtonText = (item: any): JSX.Element => {
        return <FormattedMessage id={item.text} />;
    };

    private renderListPanelBody() {
        return (
            <div>
                <NewCommandBar Commands={this.state.commands} />
                <RecordsListView
                    defaultSorting={this.state.criteria.sorting}
                    TotalPages={this.state.totalPages}
                    Records={this.state.records}
                    LoadRecordsWithNewCriteria={this.loadRecordsWithNewCriteria.bind(
                        this
                    )}
                    SelectedRecordChanged={this.selectedRecordChanged.bind(
                        this
                    )}
                />
                <Panel
                    className="panelStyle"
                    isOpen={this.state.isRecordDetailsVisibile}
                    onDismissed={this.closeRecordDetailsPanel.bind(this)}
                    type={PanelType.large}
                    onRenderBody={this.renderDetailsPanelBody.bind(this)}
                    headerText="Subject"
                    isFooterAtBottom={true}
                    //styles={{ IsFooterSticky: true }}
                    headerClassName="panelHeaderStyle"
                    hasCloseButton={false}
                    isBlocking={true}
                    onRenderHeader={this._onReadnderHader}
                >

                </Panel>
                <Dialog
                    hidden={!this.state.isRecordDeleteDialogVisibile}
                    onDismiss={this._closeDeleteRecordDialog.bind(this)}
                    dialogContentProps={{
                        type: DialogType.normal,
                        title:
                            this._cachingService.readPersistant("Language") == 0
                                ? "Delete"
                                : "Delete",
                        subText:
                            this._cachingService.readPersistant("Language") == 0
                                ? "Are you sure you want to delete the selected record?"
                                : "Are you sure you want to delete the selected record?"
                    }}
                    modalProps={{
                        titleAriaId: "myLabelId",
                        subtitleAriaId: "mySubTextId",
                        isBlocking: false,
                        containerClassName: "ms-dialogMainOverride"
                    }}
                >
                    {
                        null /** You can also include null values as the result of conditionals */
                    }
                    <DialogFooter>
                        <NewPrimaryButton
                            onClick={this.deleteRecord.bind(this)}
                            text="Delete"
                            onRenderText={this._onRenderButtonText}
                        />
                        <DefaultButton
                            onClick={this._closeDeleteRecordDialog}
                            text="Cancel"
                            onRenderText={this._onRenderButtonText}
                        />
                    </DialogFooter>
                </Dialog>
            </div>
        );
    }

    private addRecord() {
        this.setState({ isRecordDetailsVisibile: true });
        let emptyRecord = JSON.parse(JSON.stringify(this.state.emptyRecord));

        if (emptyRecord && emptyRecord.fields) {
            emptyRecord.fields.forEach((field: any) => {
                if (field.id == 305) {
                    field.data = this.props.meetingId
                    field.hidden = true;
                }
            })
        }

        this.setState({ selectedRecord: emptyRecord });
    }

    private editRecord() {
        this.setState({ isRecordDetailsVisibile: true });

        if (this.state.selectedRecord && this.state.selectedRecord.fields) {
            this.state.selectedRecord.fields.forEach((field: any) => {
                if (field.id == 305) {
                    field.hidden = true;
                }
            })
        }
    }

    private openDeleteRecordDialog() {
        this.setState({ isRecordDeleteDialogVisibile: true });
    }

    private _closeDeleteRecordDialog() {
        this.setState({ isRecordDeleteDialogVisibile: false });
    }

    private deleteRecord(button: any) {
        if (button && button.block) button.block();

        this._closeDeleteRecordDialog();

        if (this.state.selectedRecord.id) {
            this.setState({ loadingData: true });
            this._loadingService.show();
            this._recordService
                .deleteRecord(
                    this.state.selectedRecord.entityId,
                    this.state.selectedRecord.id
                )
                .then(
                    result => {
                        this.loadRecords(this.state.criteria);
                        if (button && button.block) button.block();

                        if (this.props.onExecute)
                            this.props.onExecute();

                        this._loadingService.hide();

                    },
                    error => {
                        alert(error);
                        if (button && button.block) button.block();
                        this._loadingService.hide();

                    }
                );
        }
    }

    loadRecordsWithNewCriteria = (
        sorted: number,
        sortedDescending: boolean,
        page: number
    ) => {
        const criteria = this.state.criteria;

        if (sorted > -1) {
            criteria.sorting = new Sorting();
            criteria.sorting.fieldId = sorted;
            criteria.sorting.direction = sortedDescending == true ? 1 : 0;
        } else {
            criteria.sorting = null;
        }

        criteria.pagination = new Pagination;
        criteria.pagination.start = page;
        criteria.pagination.count = this._pageSize;

        this.loadRecords(criteria);
    };

    loadRecords = (_criteria: ListRecordsCriteria) => {
        //debugger;

        this._loadingService.show();
        this._recordService.listRecords(_criteria).then(
            result => {
                let totalPages = Math.ceil(
                    result.totalNumberOfRecords / this._pageSize
                );
                this._loadingService.hide();
                this.setState(
                    {
                        totalRecords: result.totalNumberOfRecords,
                        totalPages: totalPages,
                        records: result.records,
                        //commands: this.getCommonCommands()
                    }
                );
                this._loadingService.hide();
            },
            error => {
                alert(error);
                this._loadingService.hide();
            }
        );
    };

    private _getRecord(recordId: number) {

        if (recordId > 0) {
            this._recordService.getRecord(this._entityId, recordId)
                .then(result => {

                    if (result.fields)
                        result.fields.forEach((field: RecordField) => {

                            if (field.id == 310)
                                field.hidden = true;

                        });

                    this.setState({ selectedRecord: result, commands: this.getRecordCommands(result) });
                },
                    error => {
                    })
                .catch(err => {
                });

        }
        else
            this._recordService
                .getEmptyRecord(this._entityId)
                .then(
                    result => {
                        if (result.fields)
                            result.fields.forEach((field: RecordField) => {

                                if (field.id == 310)
                                    field.hidden = true;

                            });

                        this.setState({ emptyRecord: result });
                    },
                    err => {
                    }
                )
                .catch(err => {
                });
    }

    private _saveRecord(record: any) {
        // let _this = this;
        this._loadingService.show();
        //debugger;
        return this._recordService.saveRecord(this.state.selectedRecord).then(
            result => {
                this._loadingService.hide();
                this.loadRecords(this.state.criteria);

                if (this.props.onExecute)
                    this.props.onExecute();

                this.closeRecordDetailsPanel();
            },
            err => {
                // err.response.data
                this._loadingService.hide();
            }
        );
    }

    private closeRecordDetailsPanel() {
        this.setState({ isRecordDetailsVisibile: false });
    }

    private renderDetailsPanelBody() {
        return (
            <div>
                <FieldsControl
                    isWizard={true}
                    Record={this.state.selectedRecord}
                    fields={this.state.selectedRecord.fields}
                    actions={this.state.selectedRecord.actions}
                    onSubmit={this._saveRecord.bind(this)}
                    saveAsDraft={this._saveRecord.bind(this)}
                    key={1}
                    hashKey={"1"}
                    cancelFunction={this.closeRecordDetailsPanel.bind(this)} />
            </div>
        );
    }

    private _onReadnderHader = (item: any): JSX.Element | null => {
        return (
            <div className="ms-Panel-commands" data-is-visible="true">
                <div className="ms-Panel-navigation navigation_1033a520">
                    <h2 className="panel-header-text "><FormattedMessage id={item.headerText} /></h2>
                    <IconButton className="ms-Panel-closeButton ms-PanelAction-close custom" onClick={item.onDismissed.bind(this)}
                        iconProps={{ iconName: 'ChromeClose', style: { fontSize: 12 } }}></IconButton>
                </div>
            </div>
            // <div className="panel-header-text "><FormattedMessage id={item.headerText} /></div>
        )
    }

    public render(): JSX.Element {
        return (
            <div>
                <Panel
                    className="panelStyle"
                    isOpen={this.props.open}
                    onDismissed={this.props.closePanel.bind(this)}
                    type={PanelType.large}
                    onRenderBody={this.renderListPanelBody.bind(this)}
                    headerText="Manage Subjects"
                    isFooterAtBottom={true}
                    //styles={{ IsFooterSticky: true }}
                    headerClassName="panelHeaderStyle"
                    hasCloseButton={false}
                    isBlocking={true}
                    onRenderHeader={this._onReadnderHader}
                >

                </Panel>
            </div>
        );
    }
}