/**
 * Copyright (c) 2016 - 2022 Alex Grant (@localnerve), LocalNerve LLC
 * Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms.
 */
'use strict';

var routesResponse = require('test/fixtures/routes-response');
var config = require('configs').create().data;

// setup some canned responses
var defaultResponse = 'aGVsbG8gd29ybGQK'; // base64 encoded 'hello world'
var responses = {};
// base64 encode routes-response fixture as response for FRED.url
responses[config.FRED.url()] =
  new Buffer(JSON.stringify(routesResponse)).toString(config.FRED.contentEncoding());

function Request () {
  this.__options = {};
}

Request.prototype = {
  get: function get (options, cb) {
    var body;
    var incomingMessage;
    var url = options.url || options.uri;

    // echo options for usage audit
    this.__options = options;

    // The client should not be relying on the incomingMessage if error.
    if (!this.emulateError) {
      incomingMessage = {
        statusCode: 200
      };
    }
  
    if (!this.noData) {
      body = {
        content: responses[url] || defaultResponse
      };
    }
  
    cb(
      this.emulateError ? new Error('mock error') : null,
      incomingMessage,
      body
    );  
  },
  /***
   * Mock control and audit only
   */
  get url () {
    return this.__options.url;
  },
  setEmulateError: function (value) {
    this.emulateError = value;
  },
  setNoData: function (value) {
    this.noData = value;
  }
};

module.exports = new Request();
