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

interface AppState {
  color: string;
}

class App extends Component<{}, AppState> {

  canvasRef: React.RefObject<HTMLCanvasElement>;

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

  componentDidMount() {
    this.updateCanvasImage();
  }

  componentDidUpdate() {
    this.updateCanvasImage();
  }

  updateCanvasImage() {
    let canvas = this.canvasRef.current;
    if (canvas === null) return;
    let context = canvas.getContext("2d");
    if (context === null) return;

    context.fillStyle = this.state.color;
    context.fillRect(50, 50, 150, 100);
  }

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

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

  render() {
    // We can use { and } - just like with the attributes - to put text on the screen
    return (
      <div>
        <button onClick={this.makeRed}>Red</button>
        <button onClick={this.makeBlue}>Blue</button>
        <ColorTitle color={this.state.color} />
        <canvas ref={this.canvasRef} width="300" height="300" />
      </div>
    );
  }

}

export default App;
