import { Color, ColorRepresentation, GridHelper as _GridHelper } from "three";

import * as params from "../engine/engine_default_parameters.js";
import { serializable } from "../engine/engine_serialization_decorator.js";
import { Behaviour } from "./Component.js";

/**
 * GridHelper is a component that allows to display a grid in the scene.
 * @category Helpers
 * @group Components
 */
export class GridHelper extends Behaviour {

    @serializable()
    public isGizmo: boolean = false;
    @serializable(Color)
    color0!: Color | ColorRepresentation;
    @serializable(Color)
    color1!: Color | ColorRepresentation;

    private gridHelper!: _GridHelper | null;
    private size!: number;
    private divisions!: number;
    private offset!: number;

    /** @internal */
    onEnable() {
        if (this.isGizmo && !params.showGizmos) return;

        const size = this.size;
        const divisions = this.divisions;
        if (!this.gridHelper) {
            this.gridHelper = new _GridHelper(size, divisions, this.color0 ?? new Color(.4, .4, .4), this.color1 ?? new Color(.6, .6, .6));
            if (this.offset !== undefined)
                this.gridHelper.position.y += this.offset;
        }
        if (this.gridHelper)
            this.gameObject.add(this.gridHelper);
    }

    /** @internal */
    onDisable(): void {
        if (this.gridHelper) {
            this.gameObject.remove(this.gridHelper);
            this.gridHelper = null;
        }
    }
}
