
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'


import ImageScan from '../../../../Images/Scan.png'
import ImageUpdate from '../../../../Images/Update.png'


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) {
        let DirID = sender.target.getAttribute("data-dir-id");

        if (DirID === this.GetDirectory().ID)
            return;

        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.Item некорректное работает с React ссылками */}
                    <Breadcrumb>
                        {
                            data.Path.map(function (elem, i, arr) {
                                return [
                                    <li
                                        ref={row => {
                                            if (row != null) this.NavigationElem[i] = row;
                                            else this.NavigationElem.splice(i, 1);
                                        }}

                                        key={i}
                                        className={elem.ID !== arr[arr.length - 1].ID
                                            ? "breadcrumb-item"
                                            : "breadcrumb-item active"}>
                                        {
                                            elem.ID !== arr[arr.length - 1].ID
                                            ?
                                            <Link
                                                to={'/?ID=' + elem.ID}
                                                data-dir-id={elem.ID}
                                                onClick={this.OnDirNabigationClick}

                                                role="button"
                                            >
                                                {elem.Name}
                                            </Link>
                                            :
                                            <span className="active">{elem.Name}</span>
                                        }
                                    </li>
                                ];
                            }.bind(this))
                        }
                    </Breadcrumb>

                    <ButtonGroup style={{ marginBottom: '1rem' }}>
                        <Button onClick={this.LoadDirectory} variant="secondary">
                            <img src={ImageScan} width="20" height="20" /> Обновить
                        </Button>
                        <Button onClick={this.OnScanDirClick} variant="secondary">
                            <img src={ImageUpdate} 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>
            );
        }
    }
}