
import React from 'react';
import { Link } from 'react-router-dom';
import { Button, ButtonGroup, Breadcrumb, Table, Badge } from 'react-bootstrap';

import Configuration from '../../../Tools/Configuration'
import ArrayCompare from '../../../Tools/Sort'

import FileExplorerServices from '../../../Services/FileExplorerServices'

import BaseControl from '../../BaseControl.jsx'
import FileExplorerRow from './FileExplorerRow.jsx'


export default class FileExplorerControl extends BaseControl {

    constructor(props) {
        super(props, "FileExplorerControl");

        this.state = {
            data: {},
            ShoSelectColumn: this.GetDirectory().ShoSelectColumn
        };
        this.ChildRows = [];
        this.fileExplorerServices = new FileExplorerServices();        

        this.GetDirectory().ExplorerControl = this;

        this.EventRegister.RegisterListener(this.GetDirectory().ChangeEvent, this);
        this.EventRegister.RegisterListener("OnAuthChange", this);
        this.Event_OnItemsChange_Main();
    }

    componentWillUnmount() {
        super.componentWillUnmount();
        this.GetDirectory().ExplorerControl = null;
    }

    GetDirectory() {
        return this.GlobalState[this.props.CurrentDirectoryName];
    }
    Event_OnItemsChange_Main() {
        this.LoadDirectory();
    }
    Event_OnItemsChange_Move() {
        this.LoadDirectory();
    }
    Event_OnAuthChange() {
        this.LoadDirectory();
    }



    OnBackClick(sender) {
        this.Log("OnBackClick " + this.state.data.ParentID);

        this.GetDirectory().ID = this.state.data.ParentID;
        this.EventRegister.EventAction(this.GetDirectory().ChangeEvent);
    }

    OnSortClick(sender) {
        let SortProperty = sender.target.attributes[0].value;

        let data = this.state.data;
        //debugger;
        data.items.sort(ArrayCompare(SortProperty, 1));
        this.setState({ data: data });
    }

    OnScanDirClick(sender) {
        let ID = this.GetDirectory().ID;
        this.Log("ScanDirectory " + ID);

        this.fileExplorerServices.ScanDirectoryAsync(ID).
            then(function (data) {
                this.EventRegister.EventAction(this.GetDirectory().ChangeEvent);
            }.bind(this));
    }

    //Загружает информацию о текущей папке
    LoadDirectory() {
        let ID = this.GetDirectory().ID;
        this.Log("LoadDirectory " + ID);

        this.fileExplorerServices.DirectoryGetItemsAsync(ID)
            .then(function (data) {
                this.setState({
                    data: data,
                    ShoSelectColumn: (this.GetDirectory().ShoSelectColumn && ID != -1 ? true : false)
                });
            }.bind(this));
    }

    //Получить ID данных выбранных строк
    GetSelectedID() {
        //debugger;
        return this.ChildRows.
            filter(e => e.IsCheked()).
            map(e => e.GetDataID());
    }

    //GetSelectedID(data_type) {
    //    //debugger;
    //    return this.ChildRows.
    //        filter(e => e.IsCheked() && e.state.data.ty).
    //        map(e => e.GetDataID());
    //}

    OnBeadcrumbClick(sender) {
        this.Log("OnBeadcrumbClick : ");
        //  надо установить у sender'a active режим (active = true)
        //  перед этим удалить у прежнего элемента active (active = false)
        //  осуществить "переход" в выбранную директорию
    }

    render() {
        let data = this.state.data;

        //Если данные не пусты
        if (JSON.stringify(data) !== '{}') {
            this.Log("Data");

            return (
                <div>
                    <Breadcrumb>
                        <Breadcrumb.Item onClick={this.OnBeadcrumbClick}>Home</Breadcrumb.Item>
                        <Breadcrumb.Item onClick={this.OnBeadcrumbClick}>Library</Breadcrumb.Item>
                        <Breadcrumb.Item active onClick={this.OnBeadcrumbClick}>Data</Breadcrumb.Item>
                    </Breadcrumb>

                    {this.GetDirectory().ID != Configuration.RooDirectoryID
                        ?
                        <p>
                            <Link to={`/?ID=${data.ParentID}`}>
                                <button onClick={this.OnBackClick}>
                                    l-  На уровень вверх - {data.ParentName}
                                </button>
                            </Link>
                        </p>
                        : null
                    }


                    <p>{data.LogicPath}</p>
                    <ButtonGroup>
                        <Button onClick={this.LoadDirectory} variant="secondary">
                            <img src='https://upload.wikimedia.org/wikipedia/commons/thumb/0/05/Synchronized.svg/1094px-Synchronized.svg.png' width="20" height="20" /> Обновить
                        </Button>
                        <Button onClick={this.OnScanDirClick} variant="secondary">
                            <img src='https://icts.uiowa.edu/diversity/sites/icts.uiowa.edu/files/wysiwyg_uploads/communication%20%26%20teamwork.png' width="20" height="20" /> Сканировать
                        </Button>
                    </ButtonGroup>
                    <br />
                    <Table striped bordered hover variant="dark">
                        <thead>
                            <tr>
                                <th>
                                    <Button property="ID" onClick={this.OnSortClick} variant="outline-light">ID</Button>
                                </th>
                                {
                                    this.state.ShoSelectColumn
                                        ? <th>
                                            <Button disabled variant="outline-light">Select</Button>
                                            
                                            </th>
                                        : null
                                }
                                <th>
                                    <Button property="Name" onClick={this.OnSortClick} variant="outline-light">Name</Button>
                                </th>
                                <th>
                                    <Button property="Type" onClick={this.OnSortClick} variant="outline-light">Type</Button>
                                </th>
                                <th>
                                    <Button property="Size" onClick={this.OnSortClick} variant="outline-light">Size</Button>
                                </th>
                            </tr>
                        </thead>
                        <tbody>
                            {
                                data.items.map(function (elem, i, arr) {
                                    return [
                                        <FileExplorerRow ref={row => {
                                            if (row != null) this.ChildRows[i] = row;
                                            else this.ChildRows.splice(i, 1);
                                        }}
                                            ParentComponent={this}
                                            CurrentDirectoryName={this.props.CurrentDirectoryName}
                                            key={i}

                                            ShoSelectColumn={this.state.ShoSelectColumn}
                                            data={elem}
                                        />
                                    ];
                                }.bind(this))
                            }                           
                        </tbody>
                    </Table>
                  
                </div>
            );
        }
        else {
            this.Log("NoData");

            return (
                <div>
                    <p>NoData</p>
                </div>
            );
        }
    }
}