import React,{useState} from "react";
import {Switch } from "antd"
import '../asstes/css/content.css'
import ClearIcon from '../asstes/icon/clear.png'
import CopyIcon from '../asstes/icon/copy-black.png'
import Dowmload from '../asstes/icon/download.png'
import { useDispatch,useSelector } from "react-redux";
import { updatePrintData } from "../states/global";


interface ContentRightHeaderProps {
    handleChildValue: (value: number) => void;
    hangdEditable: (value: boolean) => void;
}

const imgStyle: React.CSSProperties = { width: '25px', position: "relative", top: "-17px", cursor: "pointer" };
const ContentRightHeader: React.FC<ContentRightHeaderProps> = (props) => {
    const [active, setActive] = useState(1);
    const dispatch = useDispatch();
    const blocklyCode = useSelector((state: any) => state.blocklyCode);
    const fileName = useSelector((state: any) => state.fileName);


    const handleClick = (index: number) => {
        setActive(index);
        props.handleChildValue(index);
    }

    const clearPrintData = () => {
        dispatch(updatePrintData(""));
    }
    const switchChange = (checked: boolean) => {
        console.log("switchChange",checked);
        props.hangdEditable(checked)
    }

    const clickCopy = () => {
        navigator.clipboard.writeText(blocklyCode);
    }

    const clickDownload = () => {
        const element = document.createElement('a');
        element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(blocklyCode));
        element.setAttribute('download', (fileName || "未命名")+'.py');
        element.style.display = 'none';
        document.body.appendChild(element);
        element.click();
        document.body.removeChild(element);
    }
    return (
        <div className="content-right-header">
            <div className="content-right-header-title">
                <span className={active === 1 ? "header-text header-text-active" : 'header-text'} onClick={() => handleClick(1)}>Python 源代码</span>
                <span className={active === 2 ? "header-text header-text-active" : 'header-text'} onClick={() => handleClick(2)}>终端交互窗</span>
                <span className={active === 0 ? "header-text header-text-active" : 'header-text'} onClick={() => handleClick(0)}>串口数据显示</span>
                {active === 0 && <img src={ClearIcon} alt="clear" style={imgStyle} onClick={clearPrintData} />} 
            </div>
            <div className="content-right-header-icon">
                <Switch onChange={switchChange} />
                <img src={CopyIcon} alt="copy" onClick={() => clickCopy()}  />
                <img src={Dowmload} alt="download" onClick={() => clickDownload()} />
            </div>
        </div>
    )
}

export default ContentRightHeader;