# Copyright (c) Metakernel Development Team.
# Distributed under the terms of the Modified BSD License.


import errno
import os

from metakernel import Magic, MetaKernel, option


class FileMagic(Magic):
    @option(
        "-a",
        "--append",
        action="store_true",
        default=False,
        help="append onto an existing file",
    )
    def cell_file(self, filename: str, append: bool = False) -> None:
        """
        %%file [--append|-a] FILENAME - write contents of cell to file

        This cell magic will create or append the cell contents into/onto
        a file.

        Example:
            %%file -a log.txt
            This will append this line onto the file "log.txt"

        """
        if filename.startswith("~"):
            filename = os.path.expanduser(filename)
        filename = os.path.abspath(filename)
        # Create the path of the file if dirs don't exist:
        path = os.path.dirname(os.path.abspath(filename))
        try:
            os.makedirs(path)
        except OSError as exc:  # Python >2.5
            if exc.errno == errno.EEXIST and os.path.isdir(path):
                pass
            else:
                raise
        # Create or append to file:
        if not append:
            message = f"Created file '{filename}'."
            if os.path.isfile(self.code):
                message = f"Overwrote file '{filename}'."
        else:
            message = f"Appended on file '{filename}'."
        try:
            with open(filename, "a" if append else "w") as fp:
                fp.write(self.code)
            self.kernel.Print(message)
        except Exception as e:
            self.kernel.Error(str(e))
        self.evaluate = False


def register_magics(kernel: MetaKernel) -> None:
    kernel.register_magics(FileMagic)
