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

import {Alert, Button, Grid, IconButton, Paper, Snackbar, Tooltip, Typography} from "@mui/material";
import SaveIcon from '@mui/icons-material/Save';
import React, {useEffect, useState} from "react";
import {axiosPatch} from "../../services/AxiosService";
import ContentCopyIcon from "@mui/icons-material/ContentCopy";
import ContentPasteGoIcon from '@mui/icons-material/ContentPasteGo';
import EditableNumberSlider from "../common/EditableNumberSlider";
import DialogYesNo from "../common/DialogYesNo";

const entries = [
    {display: "Vlhkost", key: 'humidity', unit: '%', min: 0, max: 100},
    {display: "Hystereze vlhkosti", key: 'humidityHysteresis', unit: '%', min: 2, max: 15},
    {display: "Objem zalévání", key: 'pumpCycle', unit: 'ml', min: 5, max: 250},
    {display: "UV [400nm]", key: 'lightUV', unit: '%', min: 0, max: 100},
    {display: "Modrá [450nm]", key: 'lightBlue', unit: '%', min: 0, max: 100},
    {display: "Zelená [525nm]", key: 'lightGreen', unit: '%', min: 0, max: 100},
    {display: "Žlutá [595nm]", key: 'lightYellow', unit: '%', min: 0, max: 100},
    {display: "Červená [625nm]", key: 'lightRed', unit: '%', min: 0, max: 100},
    {display: "Rudá [660nm]", key: 'lightFarRed', unit: '%', min: 0, max: 100},
    {display: "IR [730nm]", key: 'lightIR', unit: '%', min: 0, max: 100},
    {display: "Aktivní od", key: 'lightHourMin', unit: 'h', min: 0, max: 23},
    {display: "Aktivní do", key: 'lightHourMax', unit: 'h', min: 0, max: 23},
];

function Preset(props) {
    const [preset, setPreset] = useState(null);
    const [isChanged, setChanged] = useState(false);
    const [editingEnabled, setEditingEnabled] = useState(false);
    const [copyText, setCopyText] = useState("");
    const [cookiePreset, setCookiePreset] = useState(null);
    const [snackOpen, setSnackOpen] = useState(false);
    const [dialogOpen, setDialogOpen] = useState(false);

    useEffect(() => {
        setEditingEnabled(props.editingEnabled || false);
        setPreset(props.preset);
    }, [props]);

    useEffect(() => {
        if (preset === null || preset === undefined) {
            return;
        }

        let data = Object.assign({}, preset);
        delete data.id;
        delete data.pumpCycle;
        delete data.devicePresetId;
        delete data.publicPresetId;

        setCopyText(JSON.stringify(data));
    }, [preset]);

    useEffect(() => {
        updateCookiePreset();
    }, []);

    const presetChanged = (value, entry) => {
        setChanged(true);

        let tmp = Object.assign({}, preset);
        tmp[entry.key] = value;
        setPreset(tmp);
    }

    const savePreset = async () => {
        setChanged(false);
        const res = await axiosPatch("/presets/data", {id: preset.id, ...preset}, {});
    }

    const updateCookiePreset = () => {
        //cookie parser https://stackoverflow.com/a/64472572/8784402
        const cookiesMap = Object.fromEntries(document.cookie.split('; ')
            .map(v => v.split(/=(.*)/s).map(decodeURIComponent)));

        const presetCookieData = cookiesMap["copiedPreset"];
        if (presetCookieData !== undefined && presetCookieData !== null) {
            const jsonPresetCookie = JSON.parse(presetCookieData);
            setCookiePreset(jsonPresetCookie);
        }
    }

    const copyPreset = () => {
        document.cookie = "copiedPreset=" + copyText;
        setSnackOpen(true);
        updateCookiePreset();
    }

    const pastePreset = () => {
        if (cookiePreset !== undefined && cookiePreset !== null) {
            const newPreset = Object.assign({}, preset, cookiePreset);
            setPreset(newPreset);
            setChanged(true);
        }
        setDialogOpen(false);
    }

    const snackHandleClose = (e, reason) => {
        if (reason === "clickaway") {
            return;
        }
        setSnackOpen(false);
    }

    return (<>
        {!!preset ?
            <Paper elevation={2} sx={{ padding: 1 }}>
                <Grid container columns={{xs: 1}}>
                    <Grid item xs={1} sx={{
                        display: "flex",
                        flexWrap: "wrap",
                        alignItems: "flex-start"
                    }}>
                        <Grid container columns={{xs: 1, sm: 2, md: 2, lg: 3}}>
                            {entries.map((entry) => (
                                <Grid item xs={1} sx={{paddingLeft: 2, paddingRight: 2, paddingBottom: 1}} key={entry.key}>
                                    <Typography gutterBottom>{entry.display}</Typography>
                                        <EditableNumberSlider value={preset[entry.key]}
                                                              min={entry.min} max={entry.max}
                                                              changeFce={(value) => presetChanged(value, entry)}
                                                              disabled={!editingEnabled}/>
                                </Grid>
                            ))}
                        </Grid>
                    </Grid>

                    <Grid item xs={1} sx={{display: "inline-flex", justifyContent: "space-between"}}>
                        <div>
                            <Tooltip title={"Kopírovat přednastavení"} followCursor>
                                <IconButton onClick={copyPreset} size={"small"}>
                                    <ContentCopyIcon fontSize={"inherit"}/>
                                </IconButton>
                            </Tooltip>

                            {editingEnabled && cookiePreset !== null &&
                                <Tooltip title={"Vložit přednastavení"} followCursor>
                                    <IconButton onClick={() => setDialogOpen(true)} size={"small"}>
                                        <ContentPasteGoIcon fontSize={"inherit"}/>
                                    </IconButton>
                                </Tooltip>
                            }
                        </div>

                        {editingEnabled && <>
                                <Button variant={"contained"}
                                        endIcon={<SaveIcon/>}
                                        disabled={!isChanged}
                                        onClick={savePreset}
                                        size={"small"}
                                        sx={{marginRight: 1}}
                                >
                                    Uložit
                                </Button>
                        </>}
                    </Grid>
                </Grid>
            </Paper>
            :
            <div/>
        }

        <DialogYesNo fceYes={pastePreset}
                     fceNo={() => setDialogOpen(false)}
                     title={"Vložit nastavení?"}
                     description={"Potvrdit přepsání nastavení"}
                     isOpen={dialogOpen}
        />

        <Snackbar open={snackOpen} onClose={snackHandleClose} autoHideDuration={6000} anchorOrigin={{vertical: 'bottom', horizontal: 'right'}}>
            <Alert onClose={snackHandleClose} severity="success" sx={{ width: '100%' }}>
                Nastavení zkopírováno!
            </Alert>
        </Snackbar>
    </>);
}


export default Preset;
