var fs = require('fs')
var path = require('path')
var log = require(path.join(__dirname, '/../log'))

var Event = function (pageName, eventName, options) {
  if (!pageName) throw new Error('Page name required')

  this.log = log.get().child({module: 'event'})

  /** The name of the page the event is attached to. */
  this.page = pageName

  /** The name of the event. */
  this.name = eventName

  this.options = options || {}
}

/**
 * Load the event file using the name specified in the constructor.
 */
Event.prototype.loadEvent = function () {
  var filepath = this.options.eventPath + '/' + this.name + '.js'

  if (filepath && !fs.existsSync(filepath)) {
    throw new Error('Page "' + this.page + '" references event "' + this.name + '" which can\'t be found in "' + this.options.eventPath + '"')
  }

  try {
    // get the event
    return require(filepath)
  } catch (err) {
    throw err
  }
}

/**
 * Run the event.
 *
 * @param {http.IncomingMessage} req - The HTTP request.
 * @param {http.ServerResponse} res - The HTTP response.
 * @param {object} data - The JSON data.
 * @param {done} done - The callback function.
 */
Event.prototype.run = function (req, res, data, done) {
  var self = this

  this.loadEvent()(req, res, data, function (err, result) {
    if (err) {
      self.log.error(err)
    }

    return done(err, result)
  })
}

/** Blend two colors together. */
module.exports = function (pageName, eventName, options) {
  return new Event(pageName, eventName, options)
}

module.exports.Event = Event
