"""
Copyright 2021 Daniel Afriyie

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""

import os
import uuid
import stat
import errno
import shutil
from typing import Optional, Callable, Any, Sequence

from ru.hints import Path
from ru.constants import constants


def get_data(
        fn: Path,
        split: bool = False,
        split_char: Optional[str] = None,
        filter_blanks: bool = False,
) -> str | list[str]:
    """
    :param fn: filename to open
    :param split: if you want to split the data read
    :param split_char: character you want to split the data on
    :param filter_blanks: remove empty strings if split=True
    Example:
    >>>data = get_data("file.txt", split=True, split_char=",")
    >>>print(data)
    [1, 2, 3, 4]
    """
    with open(fn, encoding=constants.ENCODING) as f:
        data = f.read()
        if split:
            if split_char:
                data_split = data.split(split_char)
                if filter_blanks:
                    data_split = [s.strip() for s in data_split if s.strip() != ""]
                    return data_split
                return data_split
    return data


def mk_dir(*paths: Path) -> None:
    for p in paths:
        os.makedirs(p, exist_ok=True)


def get_filename(name: str, path: Path, is_folder: bool = False) -> Path:
    if is_folder:
        return os.path.join(path, f"{name}_{uuid.uuid4()}")

    split = name.split(".")
    stemname = ".".join(split[0:-1])
    extension = split[-1]
    return os.path.join(path, f"{stemname}_{uuid.uuid4()}.{extension}")


def handle_remove_read_only(func: Callable[[Path], None], path: Path, exc: Sequence[Any]) -> None:
    excvalue = exc[1]
    if func in (os.rmdir, os.remove) and excvalue.errno == errno.EACCES:
        os.chmod(path, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
        func(path)
    else:
        raise


def remove_dir(p: Path, ignore_errors: Optional[bool] = True) -> None:
    try:
        shutil.rmtree(p, ignore_errors=False, onerror=handle_remove_read_only)
    except Exception as e:
        if not ignore_errors:
            raise e
