
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.NavigationElem = [];
        this.fileExplorerServices = new FileExplorerServices();

        //Для сортировки
        this.SortColumnProperty = "";
        //1 - Dec, -1 - Asc
        this.SortDecAsc = 0;

        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;

        if (this.SortColumnProperty != SortProperty) {
            this.SortDecAsc = 1;
            this.SortColumnProperty = SortProperty;
        }
        else 
            this.SortDecAsc = -this.SortDecAsc; 

        let data = this.state.data;
        //debugger;
        data.items.sort(ArrayCompare(SortProperty, this.SortDecAsc));
        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)
                });
                //debugger;
            }.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());
    //}

    OnDirNabigationClick(sender) {
        if (!sender.target.getAttribute("active"))
            return;

        let DirID = sender.target.getAttribute("data-dir-id");

        this.GetDirectory().ID = DirID;
        this.EventRegister.EventAction(this.GetDirectory().ChangeEvent);
    }

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

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

            return (
                <div>

                    {/*Виртуальный путь к папке*/}
                    <Breadcrumb>
                        {
                            data.Path.map(function (elem, i, arr) {
                                return [
                                    <Breadcrumb.Item ref={row => {
                                        if (row != null) this.NavigationElem[i] = row;
                                        else this.NavigationElem.splice(i, 1);
                                    }}
                                        key={i}
                                        href={`/?ID=${elem.ID}`}
                                        data-dir-id={elem.ID}
                                        onClick={this.OnDirNabigationClick}
                                        active={elem.ID !== arr[arr.length - 1].ID
                                            ? false
                                            : true}
                                    >
                                        {elem.Name}
                                    </ Breadcrumb.Item>
                                ];
                            }.bind(this))
                        }
                    </Breadcrumb>

  

                        <ButtonGroup style={{ marginBottom: '1rem' }}>
                            <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>
            );
        }
    }
}