"use strict";

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

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

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

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

// import store from '../store'
const tail = _env.default.KTRM_LOGS_TAIL;
let logs;
let logStream;

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 store => {
  if (!store.state.containers.active) {
    return;
  }

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

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

  if (store.state.containers.logs) {
    shouldClear = true;
    store.setContainerLogs('Loading ...');
  }

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

    store.appendContainerLogs(chunk);
  });
};

exports.listenForLogs = listenForLogs;

const refreshContainers = async store => {
  let containers;

  try {
    containers = await _docker.default.listContainers({
      all: true
    });
  } catch (err) {
    await store.setContainersList([]);
    await store.setDaemon(true);
    return;
  }

  await store.setDaemon(false);
  const newList = [];

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

  await store.setContainersList(newList);

  if (!store.state.containers.active) {
    await store.setContainerActive(store.state.containers.list[0]);
    listenForLogs(store);
  }
};

exports.refreshContainers = refreshContainers;