'use strict';

/* jshint ignore:start */
/**
 * This code was generated by
 * \ / _    _  _|   _  _
 *  | (_)\/(_)(_|\/| |(/_  v1.0.0
 *       /       /
 */
/* jshint ignore:end */

var Q = require('q');  /* jshint ignore:line */
var _ = require('lodash');  /* jshint ignore:line */
var util = require('util');  /* jshint ignore:line */
var Page = require('../../../base/Page');  /* jshint ignore:line */
var deserialize = require(
    '../../../base/deserialize');  /* jshint ignore:line */
var serialize = require('../../../base/serialize');  /* jshint ignore:line */
var values = require('../../../base/values');  /* jshint ignore:line */

var CallSummariesList;
var CallSummariesPage;
var CallSummariesInstance;

/* jshint ignore:start */
/**
 * Initialize the CallSummariesList
 *
 * @constructor Twilio.Insights.V1.CallSummariesList
 *
 * @param {Twilio.Insights.V1} version - Version of the resource
 */
/* jshint ignore:end */
CallSummariesList = function CallSummariesList(version) {
  /* jshint ignore:start */
  /**
   * @function callSummaries
   * @memberof Twilio.Insights.V1#
   *
   * @param {string} sid - sid of instance
   *
   * @returns {Twilio.Insights.V1.CallSummariesContext}
   */
  /* jshint ignore:end */
  function CallSummariesListInstance(sid) {
    return CallSummariesListInstance.get(sid);
  }

  CallSummariesListInstance._version = version;
  // Path Solution
  CallSummariesListInstance._solution = {};
  CallSummariesListInstance._uri = `/Voice/Summaries`;
  /* jshint ignore:start */
  /**
   * Streams CallSummariesInstance records from the API.
   *
   * This operation lazily loads records as efficiently as possible until the limit
   * is reached.
   *
   * The results are passed into the callback function, so this operation is memory
   * efficient.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @function each
   * @memberof Twilio.Insights.V1.CallSummariesList#
   *
   * @param {object} [opts] - Options for request
   * @param {string} [opts.from] - The from
   * @param {string} [opts.to] - The to
   * @param {string} [opts.fromCarrier] - The from_carrier
   * @param {string} [opts.toCarrier] - The to_carrier
   * @param {string} [opts.fromCountryCode] - The from_country_code
   * @param {string} [opts.toCountryCode] - The to_country_code
   * @param {boolean} [opts.branded] - The branded
   * @param {boolean} [opts.verifiedCaller] - The verified_caller
   * @param {boolean} [opts.hasTag] - The has_tag
   * @param {string} [opts.startTime] - The start_time
   * @param {string} [opts.endTime] - The end_time
   * @param {string} [opts.callType] - The call_type
   * @param {string} [opts.callState] - The call_state
   * @param {string} [opts.direction] - The direction
   * @param {call_summaries.processing_state_request} [opts.processingState] -
   *          The processing_state
   * @param {call_summaries.sort_by} [opts.sortBy] - The sort_by
   * @param {string} [opts.subaccount] - The subaccount
   * @param {boolean} [opts.abnormalSession] - The abnormal_session
   * @param {number} [opts.limit] -
   *         Upper limit for the number of records to return.
   *         each() guarantees never to return more than limit.
   *         Default is no limit
   * @param {number} [opts.pageSize] -
   *         Number of records to fetch per request,
   *         when not set will use the default value of 50 records.
   *         If no pageSize is defined but a limit is defined,
   *         each() will attempt to read the limit with the most efficient
   *         page size, i.e. min(limit, 1000)
   * @param {Function} [opts.callback] -
   *         Function to process each record. If this and a positional
   *         callback are passed, this one will be used
   * @param {Function} [opts.done] -
   *          Function to be called upon completion of streaming
   * @param {Function} [callback] - Function to process each record
   */
  /* jshint ignore:end */
  CallSummariesListInstance.each = function each(opts, callback) {
    if (_.isFunction(opts)) {
      callback = opts;
      opts = {};
    }
    opts = opts || {};
    if (opts.callback) {
      callback = opts.callback;
    }
    if (_.isUndefined(callback)) {
      throw new Error('Callback function must be provided');
    }

    var done = false;
    var currentPage = 1;
    var currentResource = 0;
    var limits = this._version.readLimits({
      limit: opts.limit,
      pageSize: opts.pageSize
    });

    function onComplete(error) {
      done = true;
      if (_.isFunction(opts.done)) {
        opts.done(error);
      }
    }

    function fetchNextPage(fn) {
      var promise = fn();
      if (_.isUndefined(promise)) {
        onComplete();
        return;
      }

      promise.then(function(page) {
        _.each(page.instances, function(instance) {
          if (done || (!_.isUndefined(opts.limit) && currentResource >= opts.limit)) {
            done = true;
            return false;
          }

          currentResource++;
          callback(instance, onComplete);
        });

        if (!done) {
          currentPage++;
          fetchNextPage(_.bind(page.nextPage, page));
        } else {
          onComplete();
        }
      });

      promise.catch(onComplete);
    }

    fetchNextPage(_.bind(this.page, this, _.merge(opts, limits)));
  };

  /* jshint ignore:start */
  /**
   * Lists CallSummariesInstance records from the API as a list.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @function list
   * @memberof Twilio.Insights.V1.CallSummariesList#
   *
   * @param {object} [opts] - Options for request
   * @param {string} [opts.from] - The from
   * @param {string} [opts.to] - The to
   * @param {string} [opts.fromCarrier] - The from_carrier
   * @param {string} [opts.toCarrier] - The to_carrier
   * @param {string} [opts.fromCountryCode] - The from_country_code
   * @param {string} [opts.toCountryCode] - The to_country_code
   * @param {boolean} [opts.branded] - The branded
   * @param {boolean} [opts.verifiedCaller] - The verified_caller
   * @param {boolean} [opts.hasTag] - The has_tag
   * @param {string} [opts.startTime] - The start_time
   * @param {string} [opts.endTime] - The end_time
   * @param {string} [opts.callType] - The call_type
   * @param {string} [opts.callState] - The call_state
   * @param {string} [opts.direction] - The direction
   * @param {call_summaries.processing_state_request} [opts.processingState] -
   *          The processing_state
   * @param {call_summaries.sort_by} [opts.sortBy] - The sort_by
   * @param {string} [opts.subaccount] - The subaccount
   * @param {boolean} [opts.abnormalSession] - The abnormal_session
   * @param {number} [opts.limit] -
   *         Upper limit for the number of records to return.
   *         list() guarantees never to return more than limit.
   *         Default is no limit
   * @param {number} [opts.pageSize] -
   *         Number of records to fetch per request,
   *         when not set will use the default value of 50 records.
   *         If no page_size is defined but a limit is defined,
   *         list() will attempt to read the limit with the most
   *         efficient page size, i.e. min(limit, 1000)
   * @param {function} [callback] - Callback to handle list of records
   *
   * @returns {Promise} Resolves to a list of records
   */
  /* jshint ignore:end */
  CallSummariesListInstance.list = function list(opts, callback) {
    if (_.isFunction(opts)) {
      callback = opts;
      opts = {};
    }
    opts = opts || {};
    var deferred = Q.defer();
    var allResources = [];
    opts.callback = function(resource, done) {
      allResources.push(resource);

      if (!_.isUndefined(opts.limit) && allResources.length === opts.limit) {
        done();
      }
    };

    opts.done = function(error) {
      if (_.isUndefined(error)) {
        deferred.resolve(allResources);
      } else {
        deferred.reject(error);
      }
    };

    if (_.isFunction(callback)) {
      deferred.promise.nodeify(callback);
    }

    this.each(opts);
    return deferred.promise;
  };

  /* jshint ignore:start */
  /**
   * Retrieve a single page of CallSummariesInstance records from the API.
   *
   * The request is executed immediately.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @function page
   * @memberof Twilio.Insights.V1.CallSummariesList#
   *
   * @param {object} [opts] - Options for request
   * @param {string} [opts.from] - The from
   * @param {string} [opts.to] - The to
   * @param {string} [opts.fromCarrier] - The from_carrier
   * @param {string} [opts.toCarrier] - The to_carrier
   * @param {string} [opts.fromCountryCode] - The from_country_code
   * @param {string} [opts.toCountryCode] - The to_country_code
   * @param {boolean} [opts.branded] - The branded
   * @param {boolean} [opts.verifiedCaller] - The verified_caller
   * @param {boolean} [opts.hasTag] - The has_tag
   * @param {string} [opts.startTime] - The start_time
   * @param {string} [opts.endTime] - The end_time
   * @param {string} [opts.callType] - The call_type
   * @param {string} [opts.callState] - The call_state
   * @param {string} [opts.direction] - The direction
   * @param {call_summaries.processing_state_request} [opts.processingState] -
   *          The processing_state
   * @param {call_summaries.sort_by} [opts.sortBy] - The sort_by
   * @param {string} [opts.subaccount] - The subaccount
   * @param {boolean} [opts.abnormalSession] - The abnormal_session
   * @param {string} [opts.pageToken] - PageToken provided by the API
   * @param {number} [opts.pageNumber] -
   *          Page Number, this value is simply for client state
   * @param {number} [opts.pageSize] - Number of records to return, defaults to 50
   * @param {function} [callback] - Callback to handle list of records
   *
   * @returns {Promise} Resolves to a list of records
   */
  /* jshint ignore:end */
  CallSummariesListInstance.page = function page(opts, callback) {
    if (_.isFunction(opts)) {
      callback = opts;
      opts = {};
    }
    opts = opts || {};

    var deferred = Q.defer();
    var data = values.of({
      'From': _.get(opts, 'from'),
      'To': _.get(opts, 'to'),
      'FromCarrier': _.get(opts, 'fromCarrier'),
      'ToCarrier': _.get(opts, 'toCarrier'),
      'FromCountryCode': _.get(opts, 'fromCountryCode'),
      'ToCountryCode': _.get(opts, 'toCountryCode'),
      'Branded': serialize.bool(_.get(opts, 'branded')),
      'VerifiedCaller': serialize.bool(_.get(opts, 'verifiedCaller')),
      'HasTag': serialize.bool(_.get(opts, 'hasTag')),
      'StartTime': _.get(opts, 'startTime'),
      'EndTime': _.get(opts, 'endTime'),
      'CallType': _.get(opts, 'callType'),
      'CallState': _.get(opts, 'callState'),
      'Direction': _.get(opts, 'direction'),
      'ProcessingState': _.get(opts, 'processingState'),
      'SortBy': _.get(opts, 'sortBy'),
      'Subaccount': _.get(opts, 'subaccount'),
      'AbnormalSession': serialize.bool(_.get(opts, 'abnormalSession')),
      'PageToken': opts.pageToken,
      'Page': opts.pageNumber,
      'PageSize': opts.pageSize
    });

    var promise = this._version.page({uri: this._uri, method: 'GET', params: data});

    promise = promise.then(function(payload) {
      deferred.resolve(new CallSummariesPage(this._version, payload, this._solution));
    }.bind(this));

    promise.catch(function(error) {
      deferred.reject(error);
    });

    if (_.isFunction(callback)) {
      deferred.promise.nodeify(callback);
    }

    return deferred.promise;
  };

  /* jshint ignore:start */
  /**
   * Retrieve a single target page of CallSummariesInstance records from the API.
   *
   * The request is executed immediately.
   *
   * If a function is passed as the first argument, it will be used as the callback
   * function.
   *
   * @function getPage
   * @memberof Twilio.Insights.V1.CallSummariesList#
   *
   * @param {string} [targetUrl] - API-generated URL for the requested results page
   * @param {function} [callback] - Callback to handle list of records
   *
   * @returns {Promise} Resolves to a list of records
   */
  /* jshint ignore:end */
  CallSummariesListInstance.getPage = function getPage(targetUrl, callback) {
    var deferred = Q.defer();

    var promise = this._version._domain.twilio.request({method: 'GET', uri: targetUrl});

    promise = promise.then(function(payload) {
      deferred.resolve(new CallSummariesPage(this._version, payload, this._solution));
    }.bind(this));

    promise.catch(function(error) {
      deferred.reject(error);
    });

    if (_.isFunction(callback)) {
      deferred.promise.nodeify(callback);
    }

    return deferred.promise;
  };

  /* jshint ignore:start */
  /**
   * Provide a user-friendly representation
   *
   * @function toJSON
   * @memberof Twilio.Insights.V1.CallSummariesList#
   *
   * @returns Object
   */
  /* jshint ignore:end */
  CallSummariesListInstance.toJSON = function toJSON() {
    return this._solution;
  };

  CallSummariesListInstance[util.inspect.custom] = function inspect(depth,
      options) {
    return util.inspect(this.toJSON(), options);
  };

  return CallSummariesListInstance;
};


/* jshint ignore:start */
/**
 * Initialize the CallSummariesPage
 *
 * @constructor Twilio.Insights.V1.CallSummariesPage
 *
 * @param {V1} version - Version of the resource
 * @param {Response<string>} response - Response from the API
 * @param {CallSummariesSolution} solution - Path solution
 *
 * @returns CallSummariesPage
 */
/* jshint ignore:end */
CallSummariesPage = function CallSummariesPage(version, response, solution) {
  // Path Solution
  this._solution = solution;

  Page.prototype.constructor.call(this, version, response, this._solution);
};

_.extend(CallSummariesPage.prototype, Page.prototype);
CallSummariesPage.prototype.constructor = CallSummariesPage;

/* jshint ignore:start */
/**
 * Build an instance of CallSummariesInstance
 *
 * @function getInstance
 * @memberof Twilio.Insights.V1.CallSummariesPage#
 *
 * @param {CallSummariesPayload} payload - Payload response from the API
 *
 * @returns CallSummariesInstance
 */
/* jshint ignore:end */
CallSummariesPage.prototype.getInstance = function getInstance(payload) {
  return new CallSummariesInstance(this._version, payload);
};

/* jshint ignore:start */
/**
 * Provide a user-friendly representation
 *
 * @function toJSON
 * @memberof Twilio.Insights.V1.CallSummariesPage#
 *
 * @returns Object
 */
/* jshint ignore:end */
CallSummariesPage.prototype.toJSON = function toJSON() {
  let clone = {};
  _.forOwn(this, function(value, key) {
    if (!_.startsWith(key, '_') && ! _.isFunction(value)) {
      clone[key] = value;
    }
  });
  return clone;
};

CallSummariesPage.prototype[util.inspect.custom] = function inspect(depth,
    options) {
  return util.inspect(this.toJSON(), options);
};


/* jshint ignore:start */
/**
 * Initialize the CallSummariesContext
 *
 * @constructor Twilio.Insights.V1.CallSummariesInstance
 *
 * @property {string} accountSid - The account_sid
 * @property {string} callSid - The call_sid
 * @property {call_summaries.call_type} callType - The call_type
 * @property {call_summaries.call_state} callState - The call_state
 * @property {call_summaries.processing_state} processingState -
 *          The processing_state
 * @property {Date} createdTime - The created_time
 * @property {Date} startTime - The start_time
 * @property {Date} endTime - The end_time
 * @property {number} duration - The duration
 * @property {number} connectDuration - The connect_duration
 * @property {object} from - The from
 * @property {object} to - The to
 * @property {object} carrierEdge - The carrier_edge
 * @property {object} clientEdge - The client_edge
 * @property {object} sdkEdge - The sdk_edge
 * @property {object} sipEdge - The sip_edge
 * @property {string} tags - The tags
 * @property {string} url - The url
 * @property {object} attributes - The attributes
 * @property {object} properties - The properties
 * @property {object} trust - The trust
 *
 * @param {V1} version - Version of the resource
 * @param {CallSummariesPayload} payload - The instance payload
 */
/* jshint ignore:end */
CallSummariesInstance = function CallSummariesInstance(version, payload) {
  this._version = version;

  // Marshaled Properties
  this.accountSid = payload.account_sid; // jshint ignore:line
  this.callSid = payload.call_sid; // jshint ignore:line
  this.callType = payload.call_type; // jshint ignore:line
  this.callState = payload.call_state; // jshint ignore:line
  this.processingState = payload.processing_state; // jshint ignore:line
  this.createdTime = deserialize.iso8601DateTime(payload.created_time); // jshint ignore:line
  this.startTime = deserialize.iso8601DateTime(payload.start_time); // jshint ignore:line
  this.endTime = deserialize.iso8601DateTime(payload.end_time); // jshint ignore:line
  this.duration = deserialize.integer(payload.duration); // jshint ignore:line
  this.connectDuration = deserialize.integer(payload.connect_duration); // jshint ignore:line
  this.from = payload.from; // jshint ignore:line
  this.to = payload.to; // jshint ignore:line
  this.carrierEdge = payload.carrier_edge; // jshint ignore:line
  this.clientEdge = payload.client_edge; // jshint ignore:line
  this.sdkEdge = payload.sdk_edge; // jshint ignore:line
  this.sipEdge = payload.sip_edge; // jshint ignore:line
  this.tags = payload.tags; // jshint ignore:line
  this.url = payload.url; // jshint ignore:line
  this.attributes = payload.attributes; // jshint ignore:line
  this.properties = payload.properties; // jshint ignore:line
  this.trust = payload.trust; // jshint ignore:line

  // Context
  this._context = undefined;
  this._solution = {};
};

/* jshint ignore:start */
/**
 * Provide a user-friendly representation
 *
 * @function toJSON
 * @memberof Twilio.Insights.V1.CallSummariesInstance#
 *
 * @returns Object
 */
/* jshint ignore:end */
CallSummariesInstance.prototype.toJSON = function toJSON() {
  let clone = {};
  _.forOwn(this, function(value, key) {
    if (!_.startsWith(key, '_') && ! _.isFunction(value)) {
      clone[key] = value;
    }
  });
  return clone;
};

CallSummariesInstance.prototype[util.inspect.custom] = function inspect(depth,
    options) {
  return util.inspect(this.toJSON(), options);
};

module.exports = {
  CallSummariesList: CallSummariesList,
  CallSummariesPage: CallSummariesPage,
  CallSummariesInstance: CallSummariesInstance
};
