/* global window */
window.Niwa = window.Niwa || {};

window.Niwa.AdminChatStatus = (function () {
  'use strict';

  function create(opts) {
    opts = opts || {};
    var transport = opts.transport || null;

    return {
      requestStatus: function (jobId, params) {
		return requestStatus(transport, jobId || '', params || {});
	  },
	  requestStatuses: function (jobs, params) {
		params = params || {};
		params.jobs = Array.isArray(jobs) ? jobs : [];
		return requestStatus(transport, '', params);
      }
    };
  }

  function requestStatus(transport, jobId, params) {
    if (!transport) return Promise.reject(new Error('missing_admin_chat_transport'));

    var fd = transport.baseFormData((window.NiwaAI && window.NiwaAI.status_action) || 'niwa_ai_admin_autonomy_status');
    fd.append('nonce', transport.getNonce());
    if (jobId) fd.append('job_id', String(jobId));
	if (params.requestId) fd.append('request_id', String(params.requestId));
	if (params.includeHistory) fd.append('include_history', '1');
	if (params.sinceTs) fd.append('since_ts', String(params.sinceTs));
	if (params.sinceId) fd.append('since_id', String(params.sinceId));
	if (params.jobs && params.jobs.length) fd.append('jobs', JSON.stringify(params.jobs.slice(0, 50).map(function (job) {
	  return { job_id: job.jobId || '', request_id: job.requestId || '' };
	})));

    return transport.fetchAjax(fd, false).then(function (response) {
      if (!response || !response.success || !response.data) {
        throw new Error('status_failed');
      }

      return normalizeStatus(response.data);
    });
  }

  function normalizeStatus(data) {
    data = data || {};
	var jobs = Array.isArray(data.jobs) ? data.jobs.map(normalizeStatus) : [];
    return {
      status: String(data.status || 'idle'),
      jobId: String(data.job_id || ''),
	  requestId: String(data.request_id || ''),
	  generation: parseInt(data.generation || 0, 10) || 0,
      session: String(data.session || ''),
      message: String(data.message || ''),
      answer: String(data.answer || ''),
      error: String(data.error || data.message || ''),
      createdAt: parseInt(data.created_at || 0, 10) || 0,
      startedAt: parseInt(data.started_at || 0, 10) || 0,
	  updatedAt: parseInt(data.updated_at || 0, 10) || 0,
	  history: Array.isArray(data.history) ? data.history : [],
	  jobs: jobs,
	  sequence: parseInt(data.sequence || 0, 10) || 0,
	  phase: String(data.phase || '')
    };
  }

  return {
    create: create
  };
})();
