import { Component, createRef } from "preact";

export class ToggleableBox extends Component<{
    title: string,
    id: string,
    checked?: boolean;
    onChange?: (checked: boolean) => void,
  }> {
    inputRef = createRef<HTMLInputElement>();
  
    onChangeInternal(newState: boolean) {
      console.debug(`Changed state of ${this.props.id} to ${newState}`);
      if (this.props.onChange) {
        this.props.onChange(newState);
      }
    }
  
    public forceChange(status: boolean) {
      if (this.inputRef.current) {
        let inputElement = this.inputRef.current;
        inputElement.checked = status;
      }
    }
  
    render() {
      return <>
        <div class="form-check form-switch">
          <input
            class="form-check-input" type="checkbox" role="switch"
            id={this.props.id}
            ref={this.inputRef}
            onChange={() => {
              this.onChangeInternal(this.inputRef.current.checked);
            }}
          />
          <label class="form-check-label" for={this.props.id}>{this.props.title}</label>
        </div>
      </>;
    }
  }