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

import {Button, Paper, Typography} from "@mui/material";
import React, {useState} from "react";
import {useNavigate} from "react-router-dom";
import {axiosPatch, axiosRemove} from "../../services/AxiosService";
import DialogYesNo from "../common/DialogYesNo";
import CopyButton from "../common/CopyButton";
import EditableText from "../common/EditableText";
import DeviceLastData from "./DeviceLastData";

function DeviceDetail(props) {
    const navigate = useNavigate();
    const dev = props.device;
    const [dialogOpen, setDialogOpen] = useState(false);

    const removeDevice = async () => {
        setDialogOpen(false)
        const res = await axiosRemove("/devices/" + dev.id);
        navigate("/devices");
    }

    const titleSave = async (text) => {
        const res = await axiosPatch("/devices/", {id: dev.id, name: text});
    }

    return (<>
        <DialogYesNo fceYes={removeDevice}
                     fceNo={() => setDialogOpen(false)}
                     title={"Smazat zařízení?"}
                     description={"Potvrdit smazání zařízení"}
                     isOpen={dialogOpen}
        />
        {dev !== null ?
            <Paper elevation={2} sx={{padding: 1}}>
                <EditableText text={dev.name} saveFce={titleSave} textVariant={"h6"} limit={50} canEdit={true}/>

                <Typography variant={"subtitle2"} color={"text.secondary"} display={"inline"}>{"ID: " + dev.id}</Typography>
                <CopyButton text={dev.id}/>
                <br/>

                <DeviceLastData dev={dev} sx={{paddingTop: 1, paddingBottom: 1}}/>

                <Button size={"small"} onClick={() => setDialogOpen(true)} sx={{color: "red"}}>Smazat</Button>
            </Paper>
            :
            <div/> }
    </>);
}


export default DeviceDetail;
