import React, {Component} from 'react';

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 = () => {
        let newState = {
            color: "red"
        };
        this.setState(newState);
    };

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

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


    render() {
        return (
            <div>
                <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;
