import React from 'react'
import axios from 'axios'
import { DataTable } from 'primereact/datatable';
import { Column } from 'primereact/column';
import { Dropdown } from 'primereact/dropdown';
import LoadingPage from './LoadingPage';

class PollsTable extends React.Component {  
    constructor(props) {
        super(props);

        this.state = {
            tableData : undefined,
            resultsCount: 0,
            selectedRow: null,
            waiting: false,
            checked: this.props.checked,
            inputText: this.props.text,
            view: this.props.view,
            sessionResult: this.props.sessionResult,
            voteResult: this.props.voteResult,
            member: this.props.member,
            party: this.props.party,
            session: this.props.session,
            first: 0,
            rows: 10,
            makingRequest: false
        }

        this.componentDidMount = this.componentDidMount.bind(this);
        this.componentDidUpdate = this.componentDidUpdate.bind(this);
        this.onOptionChange = this.onOptionChange.bind(this);
        this.onCustomPage = this.onCustomPage.bind(this);
    }

    onOptionChange(e) {
        this.setState({ selectedRow: e.value });
        let url = this.props.baseUrl + "hlasovani/" + e.value.id_hlasovani;
        window.open(url, '_blank');
    }

    onCustomPage(event) {
        this.setState({
            first: event.first,
            rows: event.rows
        });
    }

    apiCallWaiting() {
        // zde bude api call
        if ( this.props.view === 'text' &&  this.props.text !== '') {
            this.apiCallGeneral('pohled=' + this.props.view + '&text=' + this.props.text);
            this.setState({ makingRequest: false });
        }
        this.setState({ waiting: false });
    }

    apiCallGeneral(url) {
        this.setState({ tableData: undefined });
        this.setState({ makingRequest: true });
        axios.get(this.props.apiBaseUrl + 'votes?' + url).then((response) => {
            if(this.props.view === 'strana' && this.props.party !== null) {
                this.setState({ tableData: response.data.data });
                this.setState({ resultsCount: response.data.pocet });
                this.setState({ makingRequest: false });
            } else {
                this.setState({ tableData: response.data });
                this.setState({ makingRequest: false });
            }
        });
    }

    sessionRequest() {
        let url = '';
        if (this.props.checked === true) {
            url = '&pouze_platna=true';
        }
        if (this.props.sessionResult !== null) {
            url = url + '&vysledek_hlasovani=' + this.props.sessionResult.code;
        }
        this.apiCallGeneral('pohled=' + this.props.view + '&zasedani=' + this.props.session.code + url);
    }

    partyRequest() {
        let url = '';
        if (this.props.checked === true) {
            url = '&pouze_platna=true';
        }
        if (this.props.voteResult !== null) {
            url = url + '&vysledek_volice=' + this.props.voteResult.code;
        }
        if (this.props.sessionResult !== null) {
            url = url + '&vysledek_hlasovani=' + this.props.sessionResult.code;
        }
        this.apiCallGeneral('pohled=' + this.props.view + '&strana=' + this.props.party.code + url);
    }

    memberRequest() {
        let url = '';
        if (this.props.checked === true) {
            url = '&pouze_platna=true';
        }
        if (this.props.voteResult !== null) {
            url = url + '&vysledek_volice=' + this.props.voteResult.code;
        }
        this.apiCallGeneral('pohled=' + this.props.view + '&clen=' + this.props.member.code + url);
    }

    chooseRequest() {
        // pohled ZASEDANI
        if ( this.props.view === 'zasedani' && this.props.session !== null) {
            this.sessionRequest();
        }

        // pohled STRANA
        if ( this.props.view === 'strana' && this.props.party !== null) {
            this.partyRequest();
        }

        // pohled CLEN
        if ( this.props.view === 'clen' && this.props.member !== null) {
            this.memberRequest();
        }

        // pohled HLEDANY TEXT
        if ( this.props.view === 'text' && this.props.text !== '') {
            this.apiCallGeneral('pohled=' + this.props.view + '&text=' + this.props.text);
        }
    }

    async componentDidMount() {
        this.chooseRequest();
    }

    componentDidUpdate(prevProps) {

        window.onpopstate = e => {
            this.setState({ tableData: undefined });
            this.chooseRequest();
        }
        
        // zmenil se pohled => nutno smazat nactena data
        if (this.props.view !== prevProps.view) {
            this.setState({ tableData: undefined });
            this.setState({ makingRequest: false });
        }

        // zmenilo se cislo zasedani 
        if (this.props.session !== prevProps.session) { 
            // unset cisla zasedani => nutno smazat nactena data
            if (this.props.session === undefined) {
                this.setState({ session: null });
                this.setState({ tableData: undefined });
            }
            // pohled ZASEDANI
            if (this.props.view === 'zasedani' && this.props.session) {
                this.sessionRequest();
            }
        }

        // zmenilo se id strany 
        if (this.props.party !== prevProps.party) { 
            // pohled STRANA
            if ( this.props.view === 'strana' && this.props.party) {
                this.partyRequest();
            }
        }

        // zmenilo se id clena 
        if (this.props.member !== prevProps.member) { 
            // unset id clena => nutno smazat nactena data
            if (this.props.member === undefined) {
                this.setState({ member: null });
                this.setState({ tableData: undefined });
            }
            // pohled CLEN
            if ( this.props.view === 'clen' && this.props.member) {
                this.memberRequest();
            }
        }
        
        // zmenil se vysledek hlasovani
        if (this.props.sessionResult !== prevProps.sessionResult) {
            // pohled ZASEDANI
            if(this.props.view === 'zasedani' && this.props.session) {
                this.sessionRequest();
            }
            // pohled STRANA
            if ( this.props.view === 'strana' && this.props.party) {
                this.partyRequest();
            }
        }

        // zmenil se vysledek hlasovani clena
        if (this.props.voteResult !== prevProps.voteResult) {
            // pohled STRANA
            if ( this.props.view === 'strana' && this.props.party) {
                this.partyRequest();
            }
            // pohled CLEN
            if ( this.props.view === 'clen' && this.props.member) {
                this.memberRequest();
            }
        }

        // zmenil se checkbox validni hladovani
        if (this.props.checked !== prevProps.checked) {
            // pohled ZASEDANI
            if(this.props.view === 'zasedani' && this.props.session) {
                this.sessionRequest();
            }
            // pohled STRANA
            if ( this.props.view === 'strana' && this.props.party) {
                this.partyRequest();
            }
            // pohled CLEN
            if ( this.props.view === 'clen' && this.props.member) {
                this.memberRequest();
            }
        }


        // zmenil se text => nutnost cekat
        if (this.props.text !== prevProps.text) {
            if (this.props.view === 'text' && this.state.waiting === false) {
                this.setState({ tableData : undefined });
                this.setState({ makingRequest: true });
                setTimeout(() => {
                    this.apiCallWaiting();
                  }, 3000);
            }
            if (this.props.view === 'text') {
                this.setState({ waiting: true });
                // nove prazdny retezec
                if(this.props.text === '') {
                    this.setState({ makingRequest: false });
                }
            }
        }
    }

    resultBodyTemplate(rowData) {
        if (rowData.vysledek === 'přijato') {
            return <span><i className={'bi text-green-500 bi-check-square mr-2'}></i>{rowData.predmet_hlasovani}</span>
        }
        return <span><i className={'bi text-red-500 bi-x-square mr-2'}></i>{rowData.predmet_hlasovani}</span>
    }

    render() {
        const template = {
            layout: 'RowsPerPageDropdown CurrentPageReport PrevPageLink NextPageLink',
            'RowsPerPageDropdown': (options) => {
                const dropdownOptions = [
                    { label: 10, value: 10 },
                    { label: 20, value: 20 },
                    { label: 50, value: 50 }
                ];

                return (
                    <React.Fragment>
                        <span className="mx-1" style={{ color: 'var(--text-color)', userSelect: 'none' }}>Počet výsledků na stránku: </span>
                        <Dropdown value={options.value} options={dropdownOptions} onChange={options.onChange} />
                    </React.Fragment>
                );
            },
            'CurrentPageReport': (options) => {
                return (
                    <span style={{ color: 'var(--text-color)', userSelect: 'none', width: '120px', textAlign: 'center' }}>
                        {options.first} - {options.last} z {options.totalRecords}
                    </span>
                )
            }
        };

        return (
            <div>
                {this.state.makingRequest === true
                ?
                <LoadingPage/>
                :
                ''
                }

                { this.props.view === null
                ?
                <p className='pt-5 pb-5'>Zvolte kritérium, podle něhož chcete filtrovat jednotlivá hlasování, prosím.</p>
                :
                ''
                }

                { this.state.tableData !== undefined && this.state.tableData.length === 0
                ?
                <p className='pt-5 pb-5'>Zvoleným kritériiím neodpovídá žádné hlasování.</p>
                :
                ''
                }

                { this.props.view === 'zasedani' && (this.props.session === null || this.props.session === undefined)
                ?
                <p className='pt-5 pb-5'>Zvolte minimálně číslo zasedání, prosím.</p>
                :
                ''
                }

                { this.props.view === 'strana' && this.props.party === null
                ?
                <p className='pt-5 pb-5'>Zvolte minimálně politickou stranu, prosím.</p>
                :
                ''
                }

                { this.props.view === 'clen' && (this.props.member === null || this.props.member === undefined)
                ?
                <p className='pt-5 pb-5'>Zvolte minimálně člena/členku zastupitelstva, prosím.</p>
                :
                ''
                }

                { this.props.view === 'text' && (this.props.text === null || this.props.text.length === 0 || this.props.text === undefined)
                ?
                <p className='pt-5 pb-5'>Napište minimálně jedno klíčové slovo, prosím.</p>
                :
                ''
                }

                { this.state.tableData !== undefined && this.state.tableData.length > 0 && this.props.view === 'zasedani' && this.props.session !== null
                ?
                    <div>
                        <DataTable value={ this.state.tableData } paginator paginatorTemplate={template} first={this.state.first} rows={this.state.rows} selectionMode="single" selection={this.state.selectedRow} onSelectionChange={this.onOptionChange} onPage={this.onCustomPage} responsiveLayout="stack" breakpoint="737px">
                            <Column field="cislo_hlasovani" header="Číslo hlasování" ></Column>
                            <Column field="predmet_hlasovani" header="Předmět hlasování" body={this.resultBodyTemplate} style={{ minWidth: '75%' }}></Column>                
                        </DataTable>
                    </div>
                    :
                    ''
                }

                { this.state.tableData !== undefined && this.state.tableData.length > 0 && this.props.view === 'strana' && this.props.party !== null
                ?
                    <div>
                        {
                            this.props.voteResult !== null 
                            ? 
                            <p className="ml-2 text-500">Vybraná možnost <span className='text-primary font-bold'>{this.props.voteResult.name}</span> se vztahuje k&nbsp;jednotlivým zastupitelům a&nbsp;odpovídá <span className='text-primary font-bold'>{ this.state.resultsCount.toLocaleString('cz') }</span> záznamům. Z&nbsp;nalezených hlasování byly odstraněny duplicity.</p> 
                            : 
                            ''
                        }
                        <DataTable value={ this.state.tableData } paginator paginatorTemplate={template} first={this.state.first} rows={this.state.rows} selectionMode="single" selection={this.state.selectedRow} onSelectionChange={this.onOptionChange} onPage={this.onCustomPage} responsiveLayout="stack" breakpoint="737px">
                            <Column field="cislo_zasedani" header="Číslo zasedání" sortable></Column>
                            <Column field="cislo_hlasovani" header="Číslo hlasování" ></Column>
                            <Column field="predmet_hlasovani" header="Předmět hlasování" body={this.resultBodyTemplate} style={{ minWidth: '75%' }}></Column>                
                        </DataTable>
                    </div>
                    :
                    ''
                }

                { this.state.tableData !== undefined && this.state.tableData.length > 0 && this.props.view === 'clen' && this.props.member !== null
                ?
                    <div>
                        <DataTable value={ this.state.tableData } paginator paginatorTemplate={template} first={this.state.first} rows={this.state.rows} selectionMode="single" selection={this.state.selectedRow} onSelectionChange={this.onOptionChange} onPage={this.onCustomPage} responsiveLayout="stack" breakpoint="737px">
                            <Column field="cislo_zasedani" header="Číslo zasedání" sortable></Column>
                            <Column field="cislo_hlasovani" header="Číslo hlasování" ></Column>
                            <Column field="predmet_hlasovani" header="Předmět hlasování" body={this.resultBodyTemplate} style={{ minWidth: '75%' }}></Column>                
                        </DataTable>
                    </div>
                    :
                    ''
                }

                { this.state.tableData !== undefined && this.state.tableData.length > 0 && this.props.view === 'text' && this.props.text !== ''
                ?
                    <div>
                        <DataTable value={ this.state.tableData } paginator paginatorTemplate={template} first={this.state.first} rows={this.state.rows} selectionMode="single" selection={this.state.selectedRow} onSelectionChange={this.onOptionChange} onPage={this.onCustomPage} responsiveLayout="stack" breakpoint="737px">
                            <Column field="cislo_zasedani" header="Číslo zasedání" sortable></Column>
                            <Column field="cislo_hlasovani" header="Číslo hlasování" ></Column>
                            <Column field="predmet_hlasovani" header="Předmět hlasování" body={this.resultBodyTemplate} style={{ minWidth: '75%' }}></Column>                
                        </DataTable>
                    </div>
                    :
                    ''
                }
            </div>
        );
    }
}

export default PollsTable;
