/* eslint-disable @typescript-eslint/no-this-alias */
import type { PAGView } from './types';

// 定义拦截器方法的类型
interface InterceptorMethods {
  makeSnapshot(this: PAGView): Promise<ImageBitmap>;
  [key: string]: Function; // 添加索引签名以解决类型检查错误
}

const interceptor: InterceptorMethods = {
  makeSnapshot(this: PAGView) {
    const pagView = this;
    return new Promise((resolve, reject) => {
      pagView.makeSnapshot()
        .then((bitmap: ImageBitmap) => {
          console.log('[info]pag-web-api, 完成截图', bitmap);
          resolve(bitmap);
        })
        .catch((err: any) => reject(err));
    });
  },
};

function createProxyPAGVIew(originPAGView: PAGView): any {
  const proxyPAGView = new Proxy(originPAGView, {
    get(target, prop, receiver) {
      const value = interceptor[prop as keyof InterceptorMethods];
      if (value instanceof Function) {
        return function (this: any, ...args: any[]) {
          return value.apply(this === receiver ? target : this, args); // 兼容this方式调用
        };
      }

      return Reflect.get(target, prop, receiver);
    },
  });

  return proxyPAGView;
}

export {
  createProxyPAGVIew,
};
