import * as React from 'react';
import {
    IColumn
} from 'office-ui-fabric-react/lib/DetailsList';
import { Record } from '../Models';
import { ListView } from "./ListView"

import { DateUtils } from '../Utils';
import { IconButton } from 'office-ui-fabric-react';

export interface IData {
    columns: IColumn[];
    items: any[];
}
import ReactResizeDetector from 'react-resize-detector';

export class RecordsListView extends React.Component<any, any>
{
    private _dateUtils: DateUtils = new DateUtils();

    constructor(props: any) {
        super(props);
        this.state = {
            columns: []
        }
    }

    private loadColumns(records: Record[], count: number, renderWorkFlow: boolean) {
        //debugger;
        let _this = this;
        let columns = new Array<any>();
        if (!records || records.length == 0)
            return this.setState({ columns: columns },
                () => {
                    this.forceUpdate();
                });;


        let fields = records[0].fields
        let hasWorkflow = records[0].hasWorkflow;

        let fieldsToRender;
        if (count == 0) {
            fieldsToRender = fields;
        } else if (count == 1 && fields.length > 1) {
            fieldsToRender = [fields[0]];
        } else if (count == 2 && fields.length > 2) {
            fieldsToRender = [fields[0], fields[1]];
        } else if (count == 3 && fields.length > 3) {
            fieldsToRender = [fields[0], fields[1], fields[2]];
        } else if (count == 4 && fields.length > 4) {
            fieldsToRender = [fields[0], fields[1], fields[2], fields[3]];
        } else if (count == 5 && fields.length > 5) {
            fieldsToRender = [fields[0], fields[1], fields[2], fields[3], fields[4]];
        } else {
            fieldsToRender = fields;
        }


        fieldsToRender.forEach(field => {
            if (field.showInListView) {

                let column = {
                    id: field.id,
                    name: field.displayName,
                    fieldName: "_" + field.id.toString(),
                    dataType: 'string',
                    minWidth: 100,
                    maxWidth: 350,

                };

                switch (field.type) {
                    case 0:
                        column.dataType = 'string';
                        break;
                    case 1:
                        column.dataType = 'number';
                        break;
                    case 2:
                        column.dataType = 'number';
                        break;
                    case 3:
                        column.dataType = 'date';
                        column["onRender"] = (item?: any, index?: number, column?: IColumn) => {
                            return (
                                <div>{this._dateUtils.formatDateTime(item["_" + field.id.toString()])
                                }</div>);
                        }
                        break;
                    case 4:
                        column.dataType = 'time';
                        column["onRender"] = (item?: any, index?: number, column?: IColumn) => {
                            return (
                                <div>{
                                    this._dateUtils.formatDateTime(item["_" + field.id.toString()])
                                }
                                </div>);
                        }
                        break;
                    case 6:
                        column.dataType = 'datetime';
                        column["onRender"] = (item?: any, index?: number, column?: IColumn) => {
                            return (
                                <div>{this._dateUtils.formatDateTime(item["_" + field.id.toString()])
                                }</div>);
                        }
                        break;
                }

                columns.push(column);
            }
        });
        if (renderWorkFlow) {
            if (hasWorkflow) {
                let column = {
                    name: 'State',
                    fieldName: "workflowState",
                    dataType: 'string'
                };
                columns.push(column);
            }
        }

        if (this.props.Actions) {
            let column = {
                name: 'Actions',
                fieldName: "actions",
                // dataType: 'string'
                onRender: (item?: any, index?: number, column?: IColumn) => {
                    return (
                        <div>
                            {
                                _this.props.Actions.map((btn: any, index: any) => {
                                    return <IconButton key={'actions' + index} className="mr-15" iconProps={{ iconName: btn.iconName }} title={btn.iconName} ariaLabel={btn.iconName} onClick={this._handleListActions.bind(this, btn.actionType, item, index)} />
                                })
                            }
                        </div>
                    )
                }
            }
            columns.push(column);
        }

        // return columns;
        this.setState({ columns: columns },
            () => {
                this.forceUpdate();
            });
    }

    private loadRows(records: Record[]) {
        let items = new Array<any>();

        if (!records || records.length == 0)
            return items;

        records.forEach(record => {
            let row = { entityId: record.entityId, id: record.id, workflowState: record.state ? record.state.name : '', hasWorkflow: record.hasWorkflow };
            record.fields.forEach(field => {
                if (field.showInListView) {
                    row["_" + field.id.toString()] = field.data;

                    switch (field.type) {
                        case 2:
                            row["_" + field.id.toString()] = field.data / 100;
                            break;
                        case 7:
                            if (field.data)
                                row["_" + field.id.toString()] = "Yes";
                            else
                                row["_" + field.id.toString()] = "No";
                            break;
                        case 9:
                            if (field.data)
                                row["_" + field.id.toString()] = field.extraData.value;
                            break;
                        case 10:
                            if (field.data) {
                                field.extraData.forEach((lookup: any) => {
                                    row["_" + field.id.toString()] = lookup.value + "<Br />";
                                });
                            }
                            break;
                        case 11:
                            if (field.data)
                                row["_" + field.id.toString()] = field.extraData.name;
                            break;
                        case 12:
                            if (field.data)
                                row["_" + field.id.toString()] = field.extraData.name;
                            break;
                        case 13:
                            if (field.extraData) {
                                row["_" + field.id.toString()] = field.extraData.name;
                            }
                            break;
                    }
                }
            });
            items.push(row);
        });

        return items;
    }

    componentWillReceiveProps() {
        this.forceUpdate()
    }

    private selectedRecordChanged(entity: any) {
        if (this.props.SelectedRecordChanged)
            this.props.SelectedRecordChanged(entity);
    }

    private loadRecordsWithNewCriteria(sorted: number, sortedDescending: boolean, page: number) {
        if (this.props.LoadRecordsWithNewCriteria)
            this.props.LoadRecordsWithNewCriteria(sorted, sortedDescending, page);
    }

    private _handleListActions(actionType: any, record: any, index: number) {
        if (actionType == 0) {
            this.props.deleteItem(record, index);
        }
    }

    public render(): JSX.Element {
        return (
            this.props.Records && this.props.Records.length > 0 ?
                <ReactResizeDetector handleWidth onResize={this.onChangeWidth.bind(this)}>
                    <div>

                        <div className="">
                            <div className="list-view-style">
                                <ListView
                                    defaultSorting={this.props.defaultSorting}
                                    horizontalConstrained={true}
                                    LoadRecordsWithNewCriteria={this.loadRecordsWithNewCriteria.bind(this)}
                                    SelectedItemChanged={this.selectedRecordChanged.bind(this)}
                                    TotalPages={this.props.TotalPages}
                                    Columns={this.state.columns}
                                    Items={this.loadRows(this.props.Records)}
                                />
                            </div>
                        </div>
                    </div>
                </ReactResizeDetector>
                : <span></span>
        );
    }


    onChangeWidth(event: any) {
        //debugger;

        if (event > 1000) {
            this.loadColumns(this.props.Records, 5, false)
        } else if (event > 800) {
            this.loadColumns(this.props.Records, 3, false)
        } else if (event > 600) {
            this.loadColumns(this.props.Records, 2, false)
        } else if (event > 400) {
            this.loadColumns(this.props.Records, 1, false)
        } else {
            this.loadColumns(this.props.Records, 1, false)
        }
    }
}