from datetime import datetime
from io import DEFAULT_BUFFER_SIZE
import os
from pathlib import Path
import shutil
from typing import Any, Text
from distutils import dir_util
import logging

from . import constants

def read_file(path: Path) -> Any:
    return path.read_text()


def get_script_directory() -> Path:
    return Path(__file__).parent


def get_current_directory() -> Path:
    current_directory = Path.cwd()
    return current_directory


def write_file(path: Path, text_data) -> None:
    # create parent directory if it doesn't exist
    create_directory(path.parents[0])
    p = Path(path)
    p.write_text(text_data)


def create_directory(path) -> None:
    Path(path).mkdir(parents=True, exist_ok=True)


def delete_directory(directory_path, delete_children) -> None:
    # check if dir exists
    if dir_exists(directory_path):
        if delete_children:
            shutil.rmtree(directory_path)
        else:
            # directory is empty, delete empty directory
            Path.rmdir(directory_path)


def move_file(source, destination_directory, replace) -> None:
    if replace:
        destination_directory_path = destination_directory / source.name
        shutil.move(src=str(source), dst=str(destination_directory_path))
    else:
        shutil.move(src=str(source), dst=str(destination_directory))


def move_directory(from_directory, to_directory):
    # create an empty copy of source_directory in destination
    destination_directory_path = to_directory / from_directory.name
    create_directory(destination_directory_path)
    # copy  directory's tree to destination
    dir_util.copy_tree(src=str(from_directory), dst=str(destination_directory_path))
    # delete source directory after copying
    delete_directory(from_directory, delete_children=True)


def copy_directory(from_directory, to_directory):
    dir_util.copy_tree(src=str(from_directory), dst=str(to_directory))


def rename_file(original_path, new_file_path) -> None:
    """
    rename file with new name
    get extension from source path
    """
    original_path.rename(new_file_path)


def copy_file_to_directory(file_path, target_directory_path) -> None:
    shutil.copy(src=file_path, dst=target_directory_path)


def is_file_empty(file_path) -> bool:
    return os.stat(file_path).st_size == 0


def get_modified_date(file_path) -> str:
    modified_time = datetime.fromtimestamp(file_path.stat().st_mtime)
    modified_time_string = modified_time.strftime(constants.TIME_FORMAT)
    return modified_time_string


def file_exists(file_path) -> bool:
    return file_path.is_file()


def dir_exists(dir_path) -> bool:
    return dir_path.exists()
