import { yaml, fs } from '../common';
import { IParseResponse } from './types';

/**
 * Parse JSON and return data or error safely
 */
export function parseJson<T>(input?: string): IParseResponse<T> {
  if (!input) {
    return {};
  }
  try {
    const data = JSON.parse(input);
    return { data, error: undefined };
  } catch (err) {
    const message = `Failed to parse JSON. ${err.message}`;
    return { data: undefined, error: { message } };
  }
}

/**
 * Parse YAML and return data or error safely
 */
export function parseYaml<T>(input?: string): IParseResponse<T> {
  if (!input) {
    return {};
  }
  try {
    input = input.replace(/\t/g, '  ');
    const data = yaml.safeLoad(input);
    return { data, error: undefined };
  } catch (err) {
    const message = `Failed to parse YAML. ${err.message}`;
    return { data: undefined, error: { message } };
  }
}

/**
 * Loads a YAML file and parses it.
 */
export async function parseYamlFile<T>(path: string) {
  const file = await fs.readFile(path);
  return parseYaml<T>(file.toString());
}
