#!/usr/bin/env python3
# -*- coding=utf-8 -*-

from typing import Optional, Tuple
import os

# For all the procedures in SCAUI, return a tuple as the result
# The first element bool indicates whether the procedure succeeds
# The second element is the error message if it fails.
SCAProcedureResult = Tuple[bool, Optional[str]]


def try_write(filename: str, content: Optional[str]) -> SCAProcedureResult:
    if not os.path.exists(filename):
        return True, None
    try:
        with open(filename, "w", encoding="utf-8") as f:
            if content is not None:
                f.write(content)
            return True, None
    except PermissionError:
        return (
            False,
            (
                f"PermissionError: can not write to {filename}, because it is already"
                f" in use by another process.\n\n1. Ensure that {filename} is closed,"
                " or \n2. Specify another output filename through the `-o` option,"
                f" e.g. nsca input.txt -o {filename.replace('.csv', '-2.csv')}"
            ),
        )
