import * as React from 'react';

import { ListView } from "../../../../Controls/ListView";
import { CommandsBar } from "../../../../Controls/CommandsBar";
import {FileService} from "../../../../Services";
import {Command,File,Folder} from "../../../../Models";
import {RouteComponentProps} from 'react-router';
import { Redirect } from "react-router-dom"
import { TextField } from 'office-ui-fabric-react/lib/TextField';
import { Modal } from 'office-ui-fabric-react/lib/Modal';

import {  DefaultButton,  PrimaryButton, Breadcrumb } from 'office-ui-fabric-react/lib';
import {    
    IColumn
} from 'office-ui-fabric-react/lib/DetailsList';
import { DateUtils } from '../../../../Utils';
export class FolderDetails extends React.Component<{} & RouteComponentProps<{id:number}>, any>{

    private _fileService:FileService = new FileService();
    private _dateUtils:DateUtils = new DateUtils();
    
    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>()
        };
        this.loadColumns();
        this.loadFolder(this.props.match.params.id);
    }

    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({navigateToFolder: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 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._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});
                });
            });
        }
    }
    
    private downloadFile(){
        if(this.selectedFile){
            window.open(this._fileService.getFullPath(this.selectedFile));
        }
    }

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

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

        return commands;
    }

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

        return commands;
    }

    loadFolder(id: number) {
        this._fileService.getFolder(id)
        .then((result)=>{
            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 '/images/docx.svg';
        }
        else if(file.contentType.indexOf('ppt')>-1){
            return '/images/pptx.svg';
        }
        else if(file.contentType.indexOf('xls')>-1){
            return '/images/xlsx.svg';
        }
        else{
            return '/images/default.jpg'
        }
    }
    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: 'any',
            fieldName: "thumbnail",
            name: '',
            onRender: (item?: any, index?: number, column?: IColumn) => {
                return (
                this.isFile(item)?
                <img src={this.getFileThumbnail(item)} className={'DetailsListExample-documentIconImage'} />
                :
                <img src={this.getFolderThumbnail(item)} className={'DetailsListExample-documentIconImage'} />
                );
            }
        });
        this.state.columns.push({
            dataType: 'string',
            fieldName: "name",
            name: 'Name'
        });
        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});
    }
    public render() {
        return (
            this.state.navigateToFolder>0?
            <Redirect to={"/folder/" +this.state.navigateToFolder} push /> :
            <div>
                <div className="ms-Grid-row">
                    <div className="ms-Grid-col ms-lg10">
                        <Breadcrumb
                            items={[
                                { text: 'Workspaces', key: 'Workspace',href:"/workspace" },

                            ]}
                            ariaLabel={'Website breadcrumb'}
                        />
                    </div>
                </div>
                <div>
                    <CommandsBar Commands={this.state.commands} />
                </div>
                <div>
                <ListView
                        Items = {this.state.items} 
                        selectionModeType={false}
                        SelectedItemChanged={this.selectedItemChanged.bind(this)}
                        Columns={this.state.columns} />
                </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>
        )
    }
}

export default FolderDetails;