# -*- coding: utf-8 -*-
"""
Small useful tools for general purpose

requirement:
    Python 2.7
"""

import csv
import time
import json
import hashlib

import os


# File system tools

def mkdir(original_dir):
    """Return original dir with os.sep if not ends with it and make this dir if not exists."""
    if '~' in original_dir:
        original_dir = os.path.expanduser(original_dir)
    if not os.path.isdir(original_dir):
        os.makedirs(original_dir)
    if not original_dir.endswith(os.sep):
        original_dir += os.sep
    return original_dir


def split_path_name_ext(full_path):
    """Return path name extension of the file from its full path."""
    path_name, ext = os.path.splitext(full_path)
    path, name = os.path.split(path_name)
    return path, name, ext


def mapfile(func, top_dir, recursive=True):
    """Call func(file) for each file in top directory and return the list of results.

    Keyword arguments:
    recursive -- traverse files in the subdir (default True)
    """
    if '~' in top_dir:
        top_dir = os.path.expanduser(top_dir)
    if not os.path.isdir(top_dir):
        return None
    children = os.walk(top_dir)
    result = []
    if not recursive:
        children = [next(children)]
    for dir_path, _, files in children:
        for each in files:
            file_path = os.path.join(dir_path, each)
            result.append(func(file_path))
    return result


def loadtxt(file_path, trim=None, header=False, ignore_empty_line=False):
    """Return firstline, lines if header is True and lines if header is False
    Keyword arguments:
    trim -- chars that will be used by str.strip() (default None)