/**
 * @file yolo model
 */

import { Runner, env } from '@paddlejs/paddlejs-core';
import '@paddlejs/paddlejs-backend-webgl';
import { process } from './process';
interface ModelConfig {
    path: string;
    mean?: number[];
    std?: number[];
    needPreheat?: boolean;
}

let runner = null as Runner;
const inputShapeW = 320;
const inputShapeH = 320;

export async function load(config: ModelConfig) {
    const {
        path,
        mean,
        std,
        needPreheat = true
    } = config;

    (window as any).runner = runner = new Runner({
        modelPath: path,
        feedShape: {
            fw: inputShapeW,
            fh: inputShapeH
        },
        fill: '#000',
        targetSize: {
            height: inputShapeH,
            width: inputShapeW
        },
        mean: mean || [0, 0, 0],
        std: std || [1, 1, 1],
        needPreheat
    });

    env.set('debug', true);
    // (window as any).layerName = 'elementwise_add_6';
    const result = await runner.init();
}


export async function classify(image) {
    const res = await runner.predict(image);

    if (res && res.length) {
        const  from = [10, 10, 25, 1];
        const  to = [10, 10, 5, 5];
        const result = process(res, image, from, to, inputShapeW)
        return result;
    }

    // let canvasDiv = document.getElementById('myCanvas') as HTMLCanvasElement;
    const canvasDiv = document.createElement('canvas') as HTMLCanvasElement;
    canvasDiv.width = 128;
    canvasDiv.height = 128;
    let ctx = canvasDiv.getContext("2d");
    ctx.drawImage(image, 0.1, 0.1, 0.8, 0.8, 0, 0, 128, 128);
    return ctx.getImageData(0, 0, 128, 128);
}

