
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 SearchControl from './SearchControl.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: {},
            //SearchString: "",
            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.LoadDirectory();
    }

    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;

        this.SortData(SortProperty, null);
    }

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

        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 currentDirectory = this.GetDirectory();
        this.Log("LoadDirectory " + currentDirectory.ID);

        this
            .fileExplorerServices
            .DirectoryGetItemsAsync(currentDirectory.ID)
            .then(
                function (data) {

                    //debugger;

                    currentDirectory.CanChangeDirectoryItems
                        = data.CanWrite;

                    this.setState({
                        data: data,
                        ShoSelectColumn: (
                            this.GetDirectory().ShoSelectColumn
                            && currentDirectory.ID != -1
                                ? true
                                : false
                        )
                    });

                    this.SortData("Type", 1);

                    this
                        .EventRegister
                        .EventAction(
                            "OnItemsChange_" + this.props.CurrentDirectoryName + "_InfoLoaded",
                            null
                        );
                }
                    .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;
        //let items = [];

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

            //if (this.state.SearchString !== "") {
            //    items = data.items
            //        .filter(e => e.Name.startsWith(this.state.SearchString));
            //}
            //else
            //    items = data.items;
            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>

                        {/*
                        <SearchControl
                            CurrentDirectoryName={this.props.CurrentDirectoryName}
                        />
                        */}
                    </ButtonGroup>
                    <br />
                    <Table striped bordered hover variant="dark">
                        <thead>
                            <tr>
                                {
                                    (Configuration.EnviromentValue == 'Development')
                                        ?
                                        <th>
                                            <Button property="ID" onClick={this.OnSortClick} variant="outline-light">ID</Button>
                                        </th>
                                        : null
                                }
                                {
                                    this.state.ShoSelectColumn
                                        ? <th>
                                            <Button disabled variant="outline-light">Выбор</Button>
                                        </th>
                                        : null
                                }
                                <th>
                                    <Button property="Name" onClick={this.OnSortClick} variant="outline-light">Имя</Button>
                                </th>
                                <th>
                                    <Button property="Type" onClick={this.OnSortClick} variant="outline-light">Тип</Button>
                                </th>
                                <th>
                                    <Button property="FileExtension" onClick={this.OnSortClick} variant="outline-light">Тип файла</Button>
                                </th>
                                <th>
                                    <Button property="Size" onClick={this.OnSortClick} variant="outline-light">Размер (Mb)</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>
            );
        }
    }
}