import { CanvasView } from "../../../../../view/elements/CanvasView.js";
import EmptyView from "../../../../../view/elements/EmptyView.js";
import { buildCanvasViewFromTexture } from "../../../render/visibility/hiz/buildCanvasViewFromTexture.js";

/**
 * @param {ImpostorDescription} impostor
 * @returns {View}
 */
function makeGrid(impostor) {
    const vGrid = new CanvasView();

    vGrid.size.set(impostor.resolution, impostor.resolution);

    const ctx = vGrid.context2d;

    ctx.strokeStyle = "rgba(64,255,0,0.5)";
    ctx.lineWidth = 1;

    ctx.beginPath();

    const frame_size = impostor.resolution / impostor.frame_count;

    for (let i = 0; i < impostor.frame_count; i++) {

        ctx.moveTo(0, i * frame_size);
        ctx.lineTo(impostor.resolution, i * frame_size);
    }

    for (let i = 0; i < impostor.frame_count; i++) {
        ctx.moveTo(i * frame_size, 0);
        ctx.lineTo(i * frame_size, impostor.resolution);
    }

    ctx.stroke();

    vGrid.css({

        position: 'absolute',
        top: '0',
        left: '0'
    });
    return vGrid;
}

/**
 *
 * @param {ImpostorDescription} impostor
 * @param {THREE.WebGLRenderer} renderer
 * @param {'albedo'|'normal'|'depth'|'alpha'|'orm'} [mode]
 * @param {boolean} [show_grid]
 * @return {View}
 */
export function makeImpostorAtlasPreview({
                                             impostor,
                                             renderer,
                                             mode = 'albedo',
                                             show_grid = true
                                         }) {

    const options = {};


    switch (mode) {
        case "normal":
            options.swizzle = ['r', 'g', 'b', 1];
            options.texture = impostor.rt.texture[1]
            break
        case "alpha":
            options.swizzle = ['a', 'a', 'a', 1];
            options.texture = impostor.rt.texture[0]
            break;
        case "depth":
            options.swizzle = ['a', 'a', 'a', 1];
            options.texture = impostor.rt.texture[1]
            break;
        case "orm":
            options.swizzle = ['r', 'g', 'b', 1];
            options.texture = impostor.rt.texture[2]
            break;
        default:
            console.warn(`Unsupported mode '${mode}', defaulting to albedo`);
        //fall-through
        case 'albedo':
            options.swizzle = ['r', 'g', 'b', 1];
            options.texture = impostor.rt.texture[0]
            break;
    }

    const ctrl = buildCanvasViewFromTexture(Object.assign({ renderer }, options));

    ctrl.view.css({
        opacity: 1,
        position: 'absolute',
        top: '0',
        left: '0'
    });
    ctrl.render();

    const vContainer = new EmptyView();

    vContainer.addChild(ctrl.view);

    if (show_grid) {

        const vGrid = makeGrid(impostor);

        vContainer.addChild(vGrid);
    }

    return vContainer;
}
