/* eslint-disable @typescript-eslint/no-this-alias */
import type { PAGComposition, PAGLayer, Vector } from './types';
export declare interface Rect {
  width: number,
  height: number
}

// 定义统一的函数接口（兼容不同参数数量）
type InterceptorMethod = (this: PAGComposition, ...args: any[]) => any;

const interceptor: Record<string, InterceptorMethod> = {
  rect(this: PAGComposition): Rect {
    const pagComposition = this;
    return {
      width: pagComposition.width(),
      height: pagComposition.height(),
    };
  },
  getLayersByName(this: PAGComposition, layerName: string): PAGLayer[] {
    const pagComposition = this;

    const vectorPagLayer: Vector<PAGLayer>  = pagComposition.getLayersByName(layerName);
    const layerList: PAGLayer[] = [];
    for (let j = 0; j < vectorPagLayer.size(); j++) {
      const pagLayer = vectorPagLayer.get(j);
      layerList.push(pagLayer);
    }

    return layerList;
  },
  getLayersUnderPoint(this: PAGComposition, localX: number, localY: number): PAGLayer[] {
    const pagComposition = this;

    const vectorPagLayer: Vector<PAGLayer> = pagComposition.getLayersUnderPoint(localX, localY);
    const layerList: PAGLayer[] = [];
    for (let j = 0; j < vectorPagLayer.size(); j++) {
      const pagLayer = vectorPagLayer.get(j);
      layerList.push(pagLayer);
    }

    return layerList;
  },
};

function createProxyPAGComposition(originPAGComposition: PAGComposition): any {
  const proxyPAGComposition = new Proxy(originPAGComposition, {
    get(target, prop: keyof typeof interceptor, receiver) {
      const value = interceptor[prop];

      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 proxyPAGComposition;
}

export {
  createProxyPAGComposition,
};
