import RestClient from "./restClient.js";

export default class BaseAPI {
  url = "";
  dummy_data = null;

  constructor(option) {
    if (option.url) {
      this.url = option.url;
    }
    if (option.dummy_data) {
      this.dummy_data = option.dummy_data;
    }
  }
  async datatable(options) {
    if (this.dummy_data != null) {
      return await this.dummyResponse(this.dummy_data);
    }
    const response = await RestClient.get(`${this.url}/datatable`, { params: options });
    return response.data;
  }
  async detail(id) {
    if (this.dummy_data != null) {
      return await this.dummyResponse(this.dummy_data.data[0]);
    }
    const response = await RestClient.get(`${this.url}/${id}`);
    return response.data;
  }

  async store(payload) {
    const response = await RestClient.post(`${this.url}`, payload);
    return response.data;
  }

  async update(id, payload) {
    const response = await RestClient.patch(`${this.url}/${id}`, payload);
    return response.data;
  }

  async delete(id) {
    const response = await RestClient.delete(`${this.url}/${id}`);
    return response.data;
  }

  buildFormData(payload, prefix = null) {
    const formData = new FormData();
    const getKeyname = (key) => (prefix ? `${prefix}[${key}]` : key);

    Object.keys(payload).forEach((key) => {
      if (Array.isArray(payload[key])) {
        for (let i = 0; i < payload[key].length; i++) {
          if (payload[key][i]) {
            formData.append(getKeyname(key) + `[]`, payload[key][i]);
          }
        }
      } else if (payload[key]) {
        formData.append(getKeyname(key), payload[key]);
      }
    });

    return formData;
  }

  headersForMultipart(headers = {}) {
    return {
      "Content-Type": "multipart/form-data",
      ...headers,
    };
  }

  configForMultipart(config = {}, headers = {}) {
    return {
      ...config,
      headers: this.headersForMultipart(headers),
    };
  }

  dummyResponse(response = { result: true }, timeout = 1000) {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve(response);
      }, timeout);
    });
  }
}
