"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = exports.refreshContainers = exports.listenForLogs = exports.parseContainer = void 0;

var _reactEasyState = require("react-easy-state");

var _docker = _interopRequireDefault(require("../docker"));

var _env = _interopRequireDefault(require("../env"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

const tail = _env.default.KTRM_LOGS_TAIL;
let logs;
let logStream;
const containers = (0, _reactEasyState.store)({
  active: null,
  noDaemon: false,
  activeLogs: '',
  list: []
});

const parseContainer = container => {
  const urlImage = require('url').parse(container.Image).path;

  const image = urlImage && urlImage.startsWith('/') ? urlImage.slice(1) : container.Image;
  return {
    name: container.Names[0].slice(1),
    running: container.State === 'running',
    image,
    id: container.Id
  };
};

exports.parseContainer = parseContainer;

const listenForLogs = async () => {
  if (!containers.active) {
    return;
  }

  const container = _docker.default.getContainer(containers.active.id);

  let shouldClear = false;
  if (logs) logs.removeAllListeners();
  if (logStream) logStream.destroy();

  if (containers.activeLogs) {
    shouldClear = true;
    containers.activeLogs = 'Loading ...';
  }

  logs = await container.logs({
    follow: true,
    stdout: true,
    stderr: true,
    tail
  });
  logs.setEncoding('utf8');
  logs.on('data', chunk => {
    if (shouldClear) {
      shouldClear = false;
      containers.activeLogs = chunk;
      return;
    }

    containers.activeLogs += chunk;
  });
};

exports.listenForLogs = listenForLogs;

const refreshContainers = async () => {
  let dContainers;

  try {
    dContainers = await _docker.default.listContainers({
      all: true
    });
  } catch (err) {
    containers.list = [];
    containers.noDaemon = true;
    return;
  }

  containers.noDaemon = false;
  const newList = [];

  for (let dContainer of dContainers) {
    const container = parseContainer(dContainer);
    container.data = await _docker.default.getContainer(container.id).inspect();
    newList.push(container);
  }

  containers.list = newList;

  if (!containers.active) {
    containers.active = containers.list[0];
    listenForLogs();
  }
};

exports.refreshContainers = refreshContainers;
var _default = containers;
exports.default = _default;