import React, {Component} from 'react';
import ColorTitle from "./ColorTitle";

interface AppState {
    color: string  // The current color that's selected by the user.
}

class App extends Component<{}, AppState> {

    canvasRef: any // Could write React.RefObject<HTMLCanvasElement> if we wanted.

    constructor(props: {}) {
        super(props);
        this.canvasRef = React.createRef();
        this.state = {
            color: "blue"
        };
    }

    componentDidUpdate() {
        this.updateCanvasImage();
    }

    componentDidMount() {
        this.updateCanvasImage();
    }

    updateCanvasImage() {
        let canvas = this.canvasRef.current;
        let context = canvas.getContext("2d");
        context.fillStyle = this.state.color;
        context.fillRect(50, 50, 150, 100);
    }

    onRedClick = () => {
        this.setState({
            color: "red"
        });
    };

    onBlueClick = () => {
        this.setState({
            color: "blue"
        });
    };

    onGreenClick = () => {
        this.setState({
            color: "green"
        });
    };


    render() {
        return (
            <div>
                <ColorTitle color={this.state.color} />
                <button onClick={this.onRedClick}>Red</button>
                <button onClick={this.onBlueClick}>Blue</button>
                <button onClick={this.onGreenClick}>Green</button>
                <br />
                <canvas ref={this.canvasRef} width="500" height="500" />
            </div>
        );
    }

}

export default App;
