import React from 'react'  
import axios from 'axios'
import LoadingPage from './LoadingPage'
import SummaryVotesGraph from './SummaryVotesGraph'
import { Link } from "react-router-dom";
import { Chart } from 'primereact/chart';
import { Divider } from 'primereact/divider';
import { Tooltip } from 'primereact/tooltip';

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

        this.state = {
            basicData : undefined,
            partiesData: undefined,
            partiesStats: undefined
        }

        this.componentDidMount = this.componentDidMount.bind(this);
    }

    async componentDidMount() {
        await axios.get( this.props.apiBaseUrl + 'generalData').then((response) => {
            this.setState({basicData: response.data});
        });
        await axios.get( this.props.apiBaseUrl + 'partiesData').then((response) => {
            this.setState({partiesData: response.data});
        });
        await axios.get( this.props.apiBaseUrl + 'partiesStats').then((response) => {
            this.setState({partiesStats: response.data});
        });
    }
    
    render() {
        const { basicData, partiesData, partiesStats } = this.state;
        const { baseUrl } = this.props;

        if (basicData !== undefined && partiesData !== undefined && partiesStats !== undefined && baseUrl !== undefined) {

            let datasetsMandates = basicData.nejnovejsi_zasedani.mandaty.map((party) => 
                ({
                    label: party.strana_zkratka,
                    backgroundColor: party.strana_barva,
                    data: [
                        party.pocet_mandatu
                    ]
                })
            )

            const mandatesData = {
                labels: [''],
                datasets: datasetsMandates
            };

            let datasetsAttendance = partiesStats.map((party) => 
                ({
                    label: party.strana_zkratka,
                    backgroundColor: party.strana_barva,
                    data: [
                        party.celkova_ucast
                    ]
                })
            )

            function cmp(a,b) {
                if (a.data[0] < b.data[0]) {
                    return 1;
                }
                if (a.data[0] > b.data[0]) {
                    return -1;
                }
                return 0;
            }

            const attendanceData = {
                labels: [''],
                datasets: datasetsAttendance.sort( cmp )
            };

            const mandatesHorizontalOptions = {
                indexAxis: 'y',
                maintainAspectRatio: false,
                aspectRatio: .8,
                plugins: {
                    legend: {
                        labels: {
                            color: '#495057'
                        }
                    }
                },
                scales: {
                    x: {
                        ticks: {
                            color: '#495057'
                        },
                        grid: {
                            color: '#ebedef'
                        }
                    },
                    y: {
                        ticks: {
                            color: '#495057'
                        },
                        grid: {
                            color: '#ebedef'
                        }
                    }
                },
                'onHover': function (evt, item) {
                    if (item[0] !== undefined) {
                        evt.native.target.style.cursor = 'pointer';
                    } else {
                        evt.native.target.style.cursor = 'default';
                    }
                },
                'onClick': function (evt, item) {
                    if (item[0] !== undefined) {
                        let actItem = mandatesData.datasets[item[0].datasetIndex].label;
                        let partyId = basicData.nejnovejsi_zasedani.mandaty.find(obj => obj.strana_zkratka === actItem).strana_id;

                        // REDIRECT
                        window.location.href = baseUrl + "strany/" + partyId;
                    }
                }
            };

            const attendanceHorizontalOptions = {
                indexAxis: 'y',
                maintainAspectRatio: false,
                aspectRatio: .8,
                plugins: {
                    legend: {
                        labels: {
                            color: '#495057'
                        }
                    }
                },
                scales: {
                    x: {
                        ticks: {
                            color: '#495057'
                        },
                        grid: {
                            color: '#ebedef'
                        }
                    },
                    y: {
                        ticks: {
                            color: '#495057'
                        },
                        grid: {
                            color: '#ebedef'
                        }
                    }
                },
                'onHover': function (evt, item) {
                    if (item[0] !== undefined) {
                        evt.native.target.style.cursor = 'pointer';
                    } else {
                        evt.native.target.style.cursor = 'default';
                    }
                },
                'onClick': function (evt, item) {
                    if (item[0] !== undefined) {
                        console.log(item);
                        let actItem = attendanceData.datasets[item[0].datasetIndex].label;
                        let partyId = partiesStats.find(obj => obj.strana_zkratka === actItem).strana_id;

                        // REDIRECT
                        window.location.href = baseUrl + "strany/" + partyId;
                    }
                }
            };

            return (
                <div className="m-5 mt-0">
                    <div className='mb-5'>
                        <h1 className='text-primary'>Politické strany</h1> 
                        <p>
                            Ve funkčním obobí 8.&nbsp;zastupitelstva působilo celkem <b>{ partiesData.length }</b>&nbsp;politických subjektů, některé však pouze v&nbsp;části období.
                        </p>
                    </div>

                    <div className="grid">
                        <div className="col-12 lg:col-6">
                            <div className='flex'>
                                <h2 className='text-primary mt-3 mr-2'>Mandáty po stranách</h2>
                                <div className="flex align-items-center">
                                    <Tooltip target=".custom-target-icon" mouseTrack mouseTrackLeft={10} />
                                    <i className="custom-target-icon pi bi-info-circle p-text-secondary p-overlay-badge" data-pr-tooltip="K poslednímu zasedání" data-pr-position="bottom" style={{ fontSize: '1.25rem', cursor: 'pointer' }}>
                                    </i>
                                </div>
                            </div>
                            <div className="lg:w-10">
                                <div >
                                    <Chart type="bar" data={ mandatesData } options={ mandatesHorizontalOptions } height="250px" width="100%" />
                                </div>
                            </div>
                        </div>
                        <div className="col-12 lg:col-6">
                            <div className='flex'>
                                <h2 className='text-primary mt-3 mr-2'>Procentuální účast na hlasováních</h2>
                                <div className="flex align-items-center">
                                    <Tooltip target=".custom-target-icon" mouseTrack mouseTrackLeft={10} />
                                    <i className="custom-target-icon pi bi-info-circle p-text-secondary p-overlay-badge" 
                                        data-pr-tooltip="Poměr součtu všech hlasování, kterých se zastupitelé z dané politické strany zúčastnili, a celkového počtu hlasování (tj. včetně počtu hlasování, u nichž byli nepřítomní)" 
                                        data-pr-position="bottom" style={{ fontSize: '1.25rem', cursor: 'pointer' }}>
                                    </i>
                                </div>
                            </div>
                            <div className="lg:w-10">
                                <div >
                                    <Chart type="bar" data={ attendanceData } options={ attendanceHorizontalOptions } height="250px" width="100%" />
                                </div>
                            </div>
                        </div>
                        <div className="col-12 lg:col-6">
                            <div className='flex'>
                                <h2 className='text-primary mt-3 mr-2'>Sumarizace hlasování</h2>
                                <div className="flex align-items-center">
                                    <Tooltip target=".custom-target-icon" mouseTrack mouseTrackLeft={10} />
                                    <i className="custom-target-icon pi bi-info-circle p-text-secondary p-overlay-badge" 
                                        data-pr-tooltip="Součet všech hlasů členů příslušné politické strany; podle vybrané možnosti" 
                                        data-pr-position="bottom" style={{ fontSize: '1.25rem', cursor: 'pointer' }}>
                                    </i>
                                </div>
                            </div>
                            <div className="lg:w-10">
                                <div >
                                    <SummaryVotesGraph baseUrl={ this.props.baseUrl } partiesStats={partiesStats} />    
                                </div>
                            </div>
                        </div>
                    </div>

                    <Divider />

                    <div className='grid mt-5'>
                        {partiesData.map((party) => (
                            <div key={ party.strana_id + 'strana' } className="col-12 md:col-6 lg:col-3 px-5 mt-4 mb-4">
                                <div className='p-3 shadow-2 mb-3 flex flex-column justify-content-center border-round' style={{ width: '90%', margin: 'auto', minHeight: '160px', minWidth: '180px' }}>
                                    <h2 className='ml-2 mt-0 text-center'>
                                        <Link 
                                            style={{ color: party.strana_barva }}
                                            to={`/strany/${ party.strana_id }`}
                                            key={party.strana_id}>
                                                { party.strana_zkratka }
                                        </Link>
                                    </h2>
                                    {
                                        (basicData.nejnovejsi_zasedani.mandaty.find(obj => obj.strana_id === party.strana_id) 
                                        ? 
                                        <div className='ml-2 flex flex-row justify-content-center align-items-center'>
                                            <div className='mr-2'>
                                                <i className="pi pi-users text-3xl mr-1" style={{ color: party.strana_barva }}></i>
                                                <span className='text-3xl font-semibold' style={{ color: party.strana_barva }}>
                                                    { basicData.nejnovejsi_zasedani.mandaty.find(obj => obj.strana_id === party.strana_id).pocet_mandatu }
                                                </span>
                                            </div>
                                            <div className="text-900 text-lg mt-2">
                                                { 
                                                basicData.nejnovejsi_zasedani.mandaty.find(obj => obj.strana_id === party.strana_id).pocet_mandatu > 4 
                                                ?
                                                'mandátů'
                                                :
                                                (
                                                    basicData.nejnovejsi_zasedani.mandaty.find(obj => obj.strana_id === party.strana_id).pocet_mandatu > 1
                                                    ?
                                                    'mandáty'
                                                    :
                                                    'mandát'
                                                )}
                                            </div>
                                        </div>
                                        :
                                        <div className='ml-2 flex flex-row justify-content-center align-items-center'>
                                            <div className='mr-2'>
                                                <i className="pi pi-users text-2xl text-500 mr-1"></i> 
                                                <span className='text-3xl font-semibold text-500'>0</span> 
                                            </div>
                                            <div className="text-900 text-lg mt-2">mandátů</div>
                                        </div>
                                        )
                                    }
                                    <div className="ml-2 text-900 text-center text-lg mt-2">({ party.clenove.length } {
                                        party.clenove.length > 4 || party.clenove.length === 0
                                        ?
                                        "zastupitelů"
                                        :
                                        (
                                            party.clenove.length > 1
                                            ?
                                            "zastupitelé"
                                            :
                                            "zastupitel"
                                        )
                                    } za celé období)</div>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>
            );
        } else {
            return (
                <LoadingPage />
            );   
        }
    }
}

export default Strany
