import JSONObject from "../instances/JSONObject";

export default class JSONArray {
  innerList: Array<any>;

  constructor(value?: any) {
    if (value && typeof value === "string") {
      this.innerList = JSON.parse(value).map((item: any) => this.wrapValue(item));
    } else if (value && Array.isArray(value)) {
      this.innerList = value.map((item: any) => this.wrapValue(item));
    } else {
      this.innerList = new Array<any>();
    }
  }

  private wrapValue(value: any): any {
    if (Array.isArray(value)) {
      return new JSONArray(value);
    } else if (value && JSONObject.isPlainObject(value)) {
      return new JSONObject(value);
    }
    return value;
  }

  public length(): number {
    return this.innerList.length;
  }

  public put(item: any) {
    this.innerList.push(this.wrapValue(item));
  }

  public get(index: number): any {
    return this.innerList[index];
  }

  public toString(): string {
    const replacer = (key: string, value: any): any => {
      if (value instanceof JSONObject) {
        return value.innerMap;
      } else if (value instanceof JSONArray) {
        return value.innerList;
      }
      return value;
    };
    return JSON.stringify(this.innerList, replacer);
  }
}
