
import React from 'react';
import { Link } from 'react-router-dom';

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.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)
                });
            }.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());
    //}

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

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

            return (
                <div>
                    {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>
                    <p>
                        <button onClick={this.LoadDirectory}>
                            Update
                         </button>
                        <button onClick={this.OnScanDirClick}>
                            Rescan
                         </button>
                    </p>


                    <table>

                        <thead>
                            <tr>
                                <th>
                                    <button property="ID" onClick={this.OnSortClick}>ID</button>
                                </th>
                                {
                                    this.state.ShoSelectColumn
                                        ? <th>Select</th>
                                        : null
                                }
                                <th>
                                    <button property="Name" onClick={this.OnSortClick}>Name</button>
                                </th>
                                <th>
                                    <button property="Type" onClick={this.OnSortClick}>Type</button>
                                </th>
                                <th>
                                    <button property="Size" onClick={this.OnSortClick}>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>
            );
        }
    }
}