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

import ContentCopyIcon from "@mui/icons-material/ContentCopy";
import {Alert, IconButton, Snackbar} from "@mui/material";
import React, {useEffect} from "react";

function CopyButton(props) {
    const [open, setOpen] = React.useState(false);
    const [textContent, setTextContent] = React.useState("");

    useEffect(() => {
        setTextContent(props.text);
    }, [props.text]);

    const handleClose = (e, reason) => {
        if (reason === 'clickaway') {
            return;
        }
        setOpen(false);
    }

    const copyText = async () => {
        if (textContent !== undefined) {
            if (navigator.clipboard && window.isSecureContext) {
                navigator.clipboard.writeText(textContent).then((res) => {
                    setOpen(true);
                }).catch((e) => {
                    console.error(e);
                });
            }
            else {
                //https://stackoverflow.com/questions/51805395/navigator-clipboard-is-undefined
                const textArea = document.createElement("textarea");
                textArea.value = textContent;

                textArea.style.position = "absolute";
                textArea.style.left = "-999999px";

                document.body.prepend(textArea);
                textArea.select();

                try {
                    document.execCommand('copy');
                    setOpen(true);
                } catch (error) {
                    console.error(error);
                } finally {
                    textArea.remove();
                }
            }
        }
    }

    return (<>
        <IconButton onClick={copyText} size={"small"}>
            <ContentCopyIcon fontSize={"inherit"}/>
        </IconButton>

        <Snackbar open={open} onClose={handleClose} autoHideDuration={6000} anchorOrigin={{vertical: 'bottom', horizontal: 'right'}}>
            <Alert onClose={handleClose} severity="success" sx={{ width: '100%' }}>
                Text zkopírován: {textContent}
            </Alert>
        </Snackbar>

    </>);
}


export default CopyButton;