import * as React from 'react';

import { ListView } from "../../../../Controls";
import { FileService } from "../../../../Services";
import { Command, File, Folder } from "../../../../Models";
import { RouteComponentProps } from 'react-router';
import { TextField } from 'office-ui-fabric-react/lib/TextField';
import { Modal } from 'office-ui-fabric-react/lib/Modal';
import 'office-ui-fabric-react/lib/components/Modal/examples/Modal.Basic.Example.scss';

import { DefaultButton, PrimaryButton, Breadcrumb, Icon, DocumentCard, IBreadcrumbItem } from 'office-ui-fabric-react/lib';
import {
    IColumn
} from 'office-ui-fabric-react/lib/DetailsList';
import { DateUtils } from '../../../../Utils';
import { NewCommandBar } from '../../../../Controls/NewCommandsBar';
import { FormattedMessage } from 'react-intl';
import { LoadingService } from '../../../../Services/LoadingService';
export class FolderDetails extends React.Component<{} & RouteComponentProps<{ id: number }>, any>{

    private _fileService: FileService = new FileService();
    private _dateUtils: DateUtils = new DateUtils();
    private _loadingService = new LoadingService();

    constructor(props: {} & RouteComponentProps<{ id: number }>) {
        super(props);

        this.state = {
            folder: new Folder(),
            items: new Array<any>(),
            commands: new Array<Command>(),
            navigateToFolder: 0,
            showAddFolderModal: false,
            folderName: '',
            columns: new Array<IColumn>(),
            folderId: this.props.match.params.id
        };
        this.loadColumns();
        this.loadFolder(this.state.folderId);
    }

    private deleteFolder() {
        if (this.selectedFolder) {
            this._fileService.deleteFolder(this.selectedFolder.id).then((result) => {
                this.loadFolder(this.state.folder.id);
            });
        }
    }
    private showAddFolderModal = (): void => {
        this.setState({ showAddFolderModal: true });
    };

    private closeAddFolderModal = (): void => {
        this.setState({ showAddFolderModal: false });
    };
    private addFolder() {
        let folder: Folder = new Folder();
        folder.name = this.state.folderName;
        folder.parentFolderId = this.state.folder.id;
        this._fileService.saveFolder(folder).then((result) => {
            this.loadFolder(this.state.folder.id);
        });
    }

    private folderDetails() {
        if (this.selectedFolder) {
            this.setState({ 'folderId': this.selectedFolder.id })

            this.loadFolder(this.selectedFolder.id);
        }
    }

    private deleteFile() {
        if (this.selectedFile) {
            this._fileService.deleteFile(this.selectedFile.id).then((result) => {
                alert("deleted successfully");
                this.loadFolder(this.state.folder.id);
            });
        }
    }

    private uploadFileClicked(ctrlId: string) {
        debugger;
        let uploadFileCtrl = document.getElementById("fileUploadControl");
        if (uploadFileCtrl) {
            uploadFileCtrl.click();
        }
    }

    private uploadFile(event: any) {
        if (event.target.files && event.target.files.length > 0) {
            const formData = new FormData();

            for (let file of event.target.files)
                formData.append(file.name, file)
            this._loadingService.show();
            this._fileService.uploadFileContent(formData).then((result) => {
                let file = result;
                file.folderId = this.state.folder.id;

                this._fileService.saveFile(file).then((result) => {
                    let folder = this.state.folder;
                    folder.files.push(result);
                    this.setState({ folder: folder });
                });
                let _this = this;
                setTimeout(() => {
                    this._loadingService.hide();
                    _this.loadFolder(this.state.folderId);
                }, 1000);
            });
        }
    }

    private downloadFile() {
        if (this.selectedFile) {
            window.open(this._fileService.getFullPath(this.selectedFile));
        }
    }

    private getCommonCommands(): any[] {
        let commands = new Array<any>();
        commands.push(
            {
                key: "addFolder",
                name: "Create Folder",
                iconProps: {
                    iconName: "Add"
                },
                onClick: this.showAddFolderModal.bind(this)
            },
            {
                key: "upload",
                name: "Upload File",
                iconProps: {
                    iconName: "Upload"
                },
                onClick: this.uploadFileClicked.bind(this)
            });
        return commands;
    }

    private getFolderCommands(): any[] {
        let commands = this.getCommonCommands();
        commands.push(
            {
                key: "removeFolder",
                name: "Remove",
                iconProps: {
                    iconName: "Delete"
                },
                onClick: this.deleteFolder.bind(this)
            },
            {
                key: "folderDetails",
                name: "Details",
                iconProps: {
                    iconName: "View"
                },
                onClick: this.folderDetails.bind(this)
            });

        return commands;
    }

    private getFileCommands(): any[] {
        let commands = this.getCommonCommands();
        commands.push(
            {
                key: "removeFile",
                name: "Remove",
                iconProps: {
                    iconName: "Delete"
                },
                onClick: this.deleteFile.bind(this)
            },
            {
                key: "download",
                name: "Download",
                iconProps: {
                    iconName: "Download"
                },
                onClick: this.downloadFile.bind(this)
            });

        return commands;
    }

    loadFolder(id: number) {
        this._loadingService.show();
        this._fileService.getFolder(id)
            .then((result) => {
                this._loadingService.hide();
                this.setState({ folder: result });


                this.setState({ items: new Array<any>() });
                this.state.items.push.apply(this.state.items, result.childrenFolders)
                this.state.items.push.apply(this.state.items, result.files)

                this.setState({ items: this.state.items, commands: this.getCommonCommands() });
            });
    }

    private isFile(item: any): boolean {
        return item.contentType !== undefined;
    }

    private selectedFile: File | null;
    private selectedFolder: Folder | null;
    private selectedItemChanged(item: any) {
        if (!item)
            return;

        this.selectedFolder = item as Folder;

        if (this.isFile(item)) {
            this.setState({ commands: this.getFileCommands() });
            this.selectedFile = item;
        }
        else {
            this.setState({ commands: this.getFolderCommands() });
            this.selectedFolder = item;
        }
    }

    folderNameChanged(value: any) {
        this.setState({ folderName: value });
    };
    private getFileThumbnail(file: any): string {
        if (file.contentType.indexOf('doc') > -1) {
            return 'WordDocument';
        }
        else if (file.contentType.indexOf('ppt') > -1) {
            return 'PowerPointDocument';
        }
        else if (file.contentType.indexOf('xls') > -1) {
            return 'ExcelDocument';
        }
        else if (file.contentType.indexOf('pdf') > -1) {
            return 'PDF';
        }
        else if (file.contentType.indexOf('text') > -1) {
            return 'TextDocument';
        }
        else if (file.contentType.indexOf('image') > -1) {
            return 'FileImage';
        }
        else {
            return 'Document'
        }
    }
    // private getFolderThumbnail(folder:any):string{
    //     if(folder.thumbnail){
    //         return this._fileService.getFullPath(folder.thumbnail)
    //     }
    //     else{
    //         return '/images/defaultFolder.ico';
    //     }
    // }
    private loadColumns() {
        this.state.columns.push({
            dataType: 'string',
            fieldName: "name",
            name: 'Name',
            onRender: (item?: any, index?: number, column?: IColumn) => {
                return (
                    <div>
                        {this.isFile(item) ?
                            <Icon style={{ fontSize: '26px', 'float': 'left', 'marginRight': '10px' }}
                                iconName={this.getFileThumbnail(item)}></Icon>
                            :
                            <Icon style={{ fontSize: '26px', 'float': 'left', 'marginRight': '10px' }} iconName="FabricFolderFill"></Icon>
                        }
                        {item.name}
                    </div>
                );
            }
        });
        this.state.columns.push({
            dataType: 'string',
            fieldName: "modifiedOn",
            name: 'Date Modified',
            onRender: (item?: any, index?: number, column?: IColumn) => {
                return (
                    <div>{this._dateUtils.formatDateTime(item.modifiedOn)
                    }</div>);
            }
        });
        this.state.columns.push({
            dataType: 'string',
            fieldName: "modifiedBy",
            name: 'Modified By'
        });
        this.state.columns.push({
            dataType: 'string',
            fieldName: "fileSize",
            name: 'File Size'
        });

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

    private _onRenderItem = (item: any): JSX.Element | null => {
        //debugger;
        if (item.onClick)
            return <a style={{ cursor: 'pointer' }} onClick={item.onClick.bind(this)}><FormattedMessage id={item.text} /></a>;
        else
            return <FormattedMessage id={item.text} />;
    };

    private loadDrive() {
        window.location.href = "/#/drive/1";
    }

    public render() {
        var items: IBreadcrumbItem[] = [];
        items.push({ text: 'Drive', key: 'Drive', onClick: this.loadDrive.bind(this) })

        if (this.state.folder.id) {
            items.push({ text: this.state.folder.name, key: this.state.folder.name });
        }
        return (

            <div className="ms-Grid-row">
                <div className="ms-Grid-col ms-sm12">
                    <div className="breadcrumb-container">
                        <i className={"fal fa-file"} />
                        <Breadcrumb
                            items={items}
                            ariaLabel={'Website breadcrumb'}
                            onRenderItem={this._onRenderItem}
                        />
                    </div>
                    <div
                        className={"ms-Grid-col ms-sm12 ms-md12 ms-lg12"}
                    >
                        <input type="file" style={{ display: "none" }} id="fileUploadControl" onChange={this.uploadFile.bind(this)} />

                        <DocumentCard className="w-100p layout-card">
                            <div>
                                <NewCommandBar Commands={this.state.commands} />
                            </div>
                            <div>
                                <ListView
                                    Items={this.state.items}
                                    selectionModeType={false}
                                    SelectedItemChanged={this.selectedItemChanged.bind(this)}
                                    Columns={this.state.columns} />
                            </div>
                        </DocumentCard>
                    </div>
                    <Modal
                        isOpen={this.state.showAddFolderModal}
                        onDismiss={this.closeAddFolderModal}
                        isBlocking={true}
                        containerClassName="ms-modalExample-container">

                        <div className="ms-modalExample-header">
                            <span>Add new folder</span>
                        </div>
                        <div className="ms-modalExample-body">
                            <p>Please enter folder name</p>
                            <div style={{ margin: 20 }} >
                                <TextField placeholder="folder name" value={this.state.folderName} onChanged={this.folderNameChanged.bind(this)} />
                            </div>
                        </div>

                        <div className="ms-modalExample-footer" style={{ textAlign: 'right', margin: '8px' }}>
                            <PrimaryButton style={{ marginRight: '8px' }} onClick={() => { this.addFolder(); this.closeAddFolderModal() }} >
                                Create
                        </PrimaryButton>
                            <DefaultButton onClick={this.closeAddFolderModal}>Cancel</DefaultButton>
                        </div>
                    </Modal>
                </div>
            </div>
        )
    }
}

export default FolderDetails;