/**
 * @file yolo model
 */

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

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

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
        },
        // center: true,
        normalizeScale: 0.007843,
        mean: mean || [0.815672, 0.917631, 0.964689],
        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(img) {
    const res = await runner.predict(img);
    if (!res || !res.length) {
        return [];
    }
    // console.log(res);
    // if (!res.length) {
    //     return [];
    // }
    const cvs = runner.mediaProcessor.targetCanvas;
    const {width, height} = cvs;
    const [x1, y1, x2, y2] = res[0].slice(2);

    const resultData = getFinalPos([x1, y1, x2, y2], [inputShapeW, inputShapeH], [width, height], img);


    return resultData;
    // const cvsctx = runner.mediaProcessor.targetContext;

    // // cvsctx.strokeStyle="red";
    // // cvsctx.strokeRect(finalX, finalY, len, len);

    // document.getElementById('result').appendChild(cvs);

    // // const imgData = cvsctx.getImageData(finalX, finalY, len, len);
    // // const ratio = 128 / len;
    // // cvs.width = width * ratio;
    // // cvs.height = height * ratio;

    // // var imgData = cxt.getImageData(0,0,canvas.width,canvas.height);
    // // cvsctx.putImageData(imgData, 0, 0);

    // const outSize = 128;
    // cvs.width = outSize;
    // cvs.height = outSize;

    // const naturalW = img.naturalWidth || img.width;
    // const naturalH = img.naturalHeight || img.height;
    // const scale = naturalW / naturalH < inputShapeW / inputShapeH
    //     ? naturalH / inputShapeH
    //     : naturalW / inputShapeW;



    // // cvsctx.drawImage(img, 0.1 * naturalW, 0.1 * naturalH, 0.8 * naturalW, 0.8 * naturalW, 0, 0, outSize, outSize);
    // cvsctx.drawImage(img, finalX * scale, finalY * scale, len * scale, len * scale, 0, 0, outSize, outSize);
    // const imageData = cvsctx.getImageData(0, 0, outSize, outSize);
    // return imageData;


    // if (demoWidth < demoHeight) {
    //     // 长图
    //     demoLeft -= imgLenDiff + scaleDiff;
    //     demoTop -= scaleDiff;
    // }
    // else {
    //     demoTop -= scaleDiff - imgLenDiff;
    //     demoLeft -= scaleDiff;
    // }

    // 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");
    // const naturalW = img.naturalWidth || img.width;
    // // const scale = naturalW / img.width;
    // const scale = 1;

    // const naturalLen = scale * max * (scaleLarge + 0);
    // ctx.drawImage(img, scale * demoLeft, scale * demoTop, naturalLen, naturalLen, 0, 0, 128, 128);
    // return ctx.getImageData(0, 0, 128, 128);
}

export function getFinalPos([x1, y1, x2, y2], [inputShapeW, inputShapeH], [width, height], img) {
    const [startX, startY] = [x1 * width, y1 * height];
    const realW = (x2 - x1) * width;
    const realH = (y2 - y1) * height;

    const max = Math.max(realW, realH);
    const scaleV = 0.5;
    const len = max * (scaleV + 1);
    const lenDiff = Math.abs(realW - realH) / 2;
    const finalX = startX - scaleV / 2 * max - (realW < max ? lenDiff : 0);
    const finalY = startY - scaleV / 2 * max - (realH < max ? lenDiff : 0);
    const cvsctx = runner.mediaProcessor.targetContext;

    // cvsctx.strokeStyle="red";
    // cvsctx.strokeRect(finalX, finalY, len, len);

    const cvs = runner.mediaProcessor.targetCanvas;
    // document.getElementById('result').appendChild(cvs);

    // const imgData = cvsctx.getImageData(finalX, finalY, len, len);
    // const ratio = 128 / len;
    // cvs.width = width * ratio;
    // cvs.height = height * ratio;

    // var imgData = cxt.getImageData(0,0,canvas.width,canvas.height);
    // cvsctx.putImageData(imgData, 0, 0);

    const outSize = 128;
    cvs.width = outSize;
    cvs.height = outSize;

    const naturalW = img.naturalWidth || img.width;
    const naturalH = img.naturalHeight || img.height;
    const scale = naturalW / naturalH < inputShapeW / inputShapeH
        ? naturalH / inputShapeH
        : naturalW / inputShapeW;



    // cvsctx.drawImage(img, 0.1 * naturalW, 0.1 * naturalH, 0.8 * naturalW, 0.8 * naturalW, 0, 0, outSize, outSize);
    cvsctx.drawImage(img, finalX * scale, finalY * scale, len * scale, len * scale, 0, 0, outSize, outSize);
    const imageData = cvsctx.getImageData(0, 0, outSize, outSize);
    return imageData;
    // return [finalX, finalY, len];
}

export function getCanvasContext () {
    return runner.mediaProcessor.targetContext;
}
