import type { RequestCacheStorage, RequestOptions } from "../core/RequestCore";
import type { RequestImplementer } from "../core/RequestImplementer";
import { isNullOrEmpty } from "../utils/Utils";

export class FormData implements Record<string, any> {
  public constructor() {}

  [index: string]: any;

  // 添加字段
  append(name: string, value: any) {
    if (!this[name]) {
      this[name] = [];
    }
    this[name].push(value);
  }

  // 获取字段值
  get(name: string) {
    if (this[name]) {
      return this[name][0];
    }
    return null;
  }

  // 获取所有字段值
  getAll(name: string) {
    return this[name] || [];
  }

  // 删除字段
  delete(name: string) {
    delete this[name];
  }

  // 检查是否存在字段
  has(name: string) {
    return this[name] !== undefined;
  }

  // 设置字段值（覆盖原有值）
  set(name: string, value: any) {
    this[name] = value;
  }

  // 获取所有字段的键名
  getKeys() {
    return Object.keys(this);
  }
}
export class Response {
  public constructor(url: string, data: unknown, options: {
    headers: Record<string, unknown>,
    status: number,
  }, errMsg: string) {
    this.errMsg = errMsg;
    this.data = data;
    this.url = url;
    this.status = options.status;
    this.headers = options.headers;
    this.ok = options.status >= 200 && options.status <= 399;
  }

  get statusText() {
    return this.ok ? 'OK' : 'ERROR:' + this.status;
  }

  headers: Record<string, unknown>;
  ok: boolean;
  status: number;
  errMsg: string;
  url: string;
  data: unknown;

  json() : Promise<any> {
    return new Promise<any>((resolve, reject) => {
      if (typeof this.data === 'undefined' || isNullOrEmpty(this.data)) {
        resolve({});
        return;
      }
      if (typeof this.data === 'object') {
        resolve(this.data);
        return;
      }
      let data = null;
      
      if (typeof this.data === 'string') {
        try {
          data = JSON.parse(this.data);
        } catch(e) {
          console.log('json error: ' + e,  this.data);
          
          reject(e);
        }
      } else {
        data = this.data;
      }

      resolve(data);
    })
  }
}

const uniappImplementer : RequestImplementer = {
  getCache: function (key: string) {
    return new Promise<RequestCacheStorage|null>((resolve, reject) => {
      uni.getStorage({
        key: key,
        success: (res) => {
          resolve(res.data ? JSON.parse(res.data) as RequestCacheStorage : null);
        },
        fail: (res) => {
          resolve(null);
        }
      });
    });
  },
  setCache: async function (key: string, value: RequestCacheStorage|null) {
    return new Promise<void>((resolve, reject) => {
      uni.setStorage({
        key: key,
        data: JSON.stringify(value),
        success: (res) => {
          resolve();
        },
        fail: (res) => {
          resolve();
        }
      });
    });
  },
  doRequest: function (url: string, init?: RequestOptions, timeout?: number): Promise<Response> {
    return new Promise<Response>((resolve, reject) => {
      uni.request({
        url: url,
        timeout: timeout,
        ...init,
        success(res) {
          const response = new Response(url, res.data, {
            headers: res.header,
            status: res.statusCode,
          }, 'success');
          resolve(response);
        },
        fail(res) {
          reject(res);
        },
      })
    });
  }
};

export default uniappImplementer;