const fs = require('fs');
const request = require('request');

const throwError = (msg = 'Something went wrong!!!') => {
  throw msg;
  process.exit(0);
};

const getFile = (url) => new Promise((resolve, reject) => {
  try {
    const content = fs.readFileSync(url, 'utf8');
    return resolve(JSON.parse(content));
  } catch {
    resolve({});
  };
});

const getApiHtml = (body, proxy) => new Promise((resolve, reject) => {
  try {
    const requestOptions = {
      url: 'https://asfand.dev/api-html/return-html',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body,
    };

    if (proxy) {
      requestOptions.proxy = proxy;
    }

    const req  = request(
    requestOptions,
    (err, res, body) => {
      if (err) {
        return throwError(err);
      }

      try {
        const res = JSON.parse(body);
        const {error, html} = res;
        
        if (error) {
          return throwError(error);
        }

        resolve(html);
      } catch (e) {
        return throwError(e);
      }
    });
  } catch (e) {
    return throwError(e);
  }
});

module.exports = {
  getApiHtml,
  getFile,
  throwError,
};
