/**
 * @file DevicesPage.js
 * @author Radim Buráň (xburan03@stud.fit.vutbr.cz)
 */

import {axiosGet, axiosPost} from "../../services/AxiosService";
import React, {useEffect, useState} from "react";
import Device from "../../components/devices/Device";
import {Grid} from "@mui/material";
import {useAuth} from "../../services/AuthMiddleware";
import {isAdmin} from "../../util/AuthInfo";
import {useNavigate} from "react-router-dom";
import FilterComponent, {Types} from "../../components/common/FilterComponent";
import CenteredCircularProgress from "../../components/common/CenteredCircularProgress";
import Paginator from "../../components/common/Paginator";

function DevicesPage() {
    const [devices, setDevices] = useState({});
    const [showAll, setShowAll] = useState(false);
    const [ownerFilter, setOwnerFilter] = useState("");
    const [nameFilter, setNameFilter] = useState("");
    const [isLoading, setLoading] = useState(true);
    const [page, setPage] = useState(1);
    const [itemsPerPage, setItemsPerPage] = useState(5);
    const [pageCount, setPageCount] = useState(1);
    const [totalItemCount, setTotalItemCount] = useState(0);
    const auth = useAuth();
    const navigate = useNavigate();

    const FILTER_OBJ = [
        {id: "newDevice", name: "Nový květináč", type: Types.BUTTON, fce: () => createNewDevice()},
        {id: "name", name: "Název", type: Types.STRING, defValue: null, fce: (str) => setNameFilter(str)},

        {id: "perPage", name: "Na stránce", type: Types.SELECT, defValue: 5, fce: (val) => setItemsPerPage(val),
            items: [
                {val: 1, name: "1"},
                {val: 2, name: "2"},
                {val: 3, name: "3"},
                {val: 4, name: "4"},
                {val: 5, name: "5"},
                {val: 10, name: "10"},
                {val: 15, name: "15"},
                {val: 25, name: "25"},
                {val: 50, name: "50"}
            ]
        },
    ]

    if (isAdmin(auth?.user)) {
        FILTER_OBJ.splice(1, 0, {id: "all", name: "Všechna zařízení", type: Types.BOOLEAN, defValue: false, fce: setShowAll});
        FILTER_OBJ.splice(3, 0, {id: "owner", name: "Uživatel", type: Types.STRING, defValue: null, fce: (str) => setOwnerFilter(str)});
    }

    useEffect(() => {
        setLoading(true);
        let filter = {presets: true};
        if (ownerFilter !== "" && ownerFilter !== null && ownerFilter !== undefined) {
            filter["owner"] = ownerFilter;
        }
        if (nameFilter !== "" && nameFilter !== null && nameFilter !== undefined) {
            filter["name"] = nameFilter;
        }

        filter["max_items"] = itemsPerPage;
        filter["page"] = page - 1;

        axiosGet("/devices" + (showAll ? "" : "/my"), filter)
        .then((res) => {
            setTotalItemCount(res.data.count);
            setDevices(res.data.items);
            setLoading(false);
        }).catch((e) => {
            console.error(e);
        });
    }, [showAll, ownerFilter, nameFilter, page, itemsPerPage]);

    useEffect(() => {
        const cnt = Math.ceil(totalItemCount/itemsPerPage);
        setPageCount(cnt);
    }, [totalItemCount, itemsPerPage]);

    useEffect(() => {
        if (page !== 1) {
            setPage(1);
        }
    }, [nameFilter, ownerFilter]);

    const createNewDevice = async () => {
        const res = await axiosPost("/devices", {
            ownerID: auth.user.id,
            name: "Nový květináč"
        });
        navigate("/devices/" + res.data.id);
    }

    return (<>
        <FilterComponent entries={FILTER_OBJ}/>

        {isLoading ?
            <CenteredCircularProgress/>
            :
            <Grid container columns={{xs: 1, sm: 2, md: 3, lg: 4}} spacing={2}>
                {Array.from(devices).map((dev, _) => {
                    return <Grid item xs={1} key={dev.id}>
                    <Device device={dev}/>
                    </Grid>;
                })}
            </Grid>
        }

        <Paginator page={page} pageCount={pageCount} pageChanged={(val) => setPage(val)} bottomPinned={true}/>
    </>);
}


export default DevicesPage