/*
 * Copyright (C) SapphireCode - All Rights Reserved
 * This file is part of Snippeteer which is released under BSD-3-Clause.
 * See file 'LICENSE' for full license details.
 * Created by Timo Hocker <timo@scode.ovh>, May 2020
 */

import path from 'path';
import child_process from 'child_process';
import fs from 'fs-extra';

/**
 * write a template to a file
 *
 * @param contents - file contents
 * @param destination - file destination
 */
async function apply_template (
  contents: string,
  destination: string
): Promise<void> {
  const dst = path.join (process.cwd (), destination);
  if (!await fs.pathExists (dst)) {
    await fs.mkdirp (path.dirname (dst));
    await fs.writeFile (dst, contents);
  }
}

type JSONMutator = {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  (json: any): any;
}

/**
 * modify a json file
 *
 * @param func - function that modifies the object
 * @param json_path - path of json file
 */
async function modify_json (
  func: JSONMutator,
  json_path = 'package.json'
): Promise<void> {
  const file_path = path.join (process.cwd (), json_path);
  const content = JSON.parse (await fs.readFile (file_path, 'utf-8'));
  const new_obj = await func (content);
  if (typeof new_obj === 'undefined' || new_obj === null)
    return;
  await fs.writeFile (file_path, JSON.stringify (new_obj, null, 2));
}

/**
 * run a command
 *
 * @param command - command to run
 * @param folder - folder to run in
 */
function run_command (command: string, folder = ''): void {
  // eslint-disable-next-line no-sync
  child_process.execSync (
    command,
    { cwd: path.join (process.cwd (), folder), stdio: 'inherit' }
  );
}

export { modify_json, apply_template, run_command };