import { join } from "path";

import { RunServiceOptions } from "../typings/run-service-options";

import Local from "../runners/local";
import Docker from "../runners/docker";
import { getAndValidate, getAndValidateService } from "./service-up";

import * as os from "os";
import { readfile } from "../helpers/fs-readfile-json";
import { writefile } from "../helpers/fs-writefile";
import { find } from "lodash";
import { exitWithMsg } from "../helpers/exit-with-msg";
import { StoreService } from "../typings/store-service";
import chalk from "chalk";
import getStore from "../helpers/get-store";

async function checkIfAlreadyDown(_yamlContent: any, serviceName: string) {
  const store = await getStore();
  const data = store.get("services") || [];
  const service = find(data, { service: serviceName });
  if (service && service.status === "down") {
    await exitWithMsg(`> "${serviceName}" service is already down`);
  }

  return service;
}

export default async (serviceName: string): Promise<void> => {
  const { _yamlPath, _yamlContent } = await getAndValidate(serviceName);

  const { servicePath, _serviceYamlPath, _ymlPath, yamlPath, content } =
    await getAndValidateService(serviceName, _yamlContent);

  const service: StoreService = await checkIfAlreadyDown(
    _yamlContent,
    serviceName,
  );

  if (service.platform) {
    const { envfile, build } = content.platforms[service.platform];
    switch (service.platform) {
      case "docker":
        await Docker.stop(
          content.container_name,
          servicePath,
          build,
          [],
          envfile,
        );
        break;
      case "local":
        await Local.stop(servicePath, build);
        break;
    }
  }

  const store = await getStore();
  const data: any = store.get("services") || [];
  let found = false;
  const json: StoreService = {
    service: serviceName,
    status: "down",
    platform: undefined,
    port: undefined,
  };
  data.map((service: any, index: number): any => {
    if (service.service === serviceName) {
      found = true;
      data[index] = json;
    }
  });
  if (!found) {
    data.push(json);
  }
  store.set("services", data);

  console.log(
    chalk.green(
      `\n"${serviceName}" is down from ${service.platform} platform\n`,
    ),
  );

  store.save();
};
