# Bryan Schumaker (8/7/2010)

import libsaria
import os

commonprefix = os.path.commonprefix
exists   = os.path.exists
is_dir   = os.path.isdir
expand   = os.path.expanduser
splitext = os.path.splitext
basename = os.path.basename
join     = os.path.join
makedir  = os.mkdir
rm       = os.remove
ls       = os.listdir
walk     = os.walk
sep      = os.sep
cwd      = os.getcwd
stat     = os.stat

cp         = None
saria_dir  = None
plugin_dir = None
make_tree  = None

shutil = None
FSTree = None
s_dir  = None
p_dir  = None

def file_id(path):
	if exists(path):
		return stat(path).st_ino
	return -1

def saria_dir_once():
	global s_dir
	global saria_dir
	s_dir = join(expand("~"), ".saria")
	if exists(s_dir) == False:
		mkdir(s_dir)
	saria_dir = saria_dir_rest
	return s_dir
def saria_dir_rest():
	global s_dir
	return s_dir
saria_dir = saria_dir_once


def plugin_dir_once():
	global p_dir
	global saria_dir
	saria = saria_dir()
	dir = "plugins"
	if libsaria.__dev__ == True:
		dir += "-dev"
	p_dir = join(saria, dir)
	if exists(p_dir) == False:
		mkdir(p_dir)
	plugin_dir = plugin_dir_rest
	return p_dir
def plugin_dir_rest():
	global p_dir
	return p_dir
plugin_dir = plugin_dir_once

def cp_once(src, dest):
	global cp
	global shutil
	import shutil
	cp = shutil.copy
	cp(src, dest)
cp = cp_once

def mkdir(path):
	if not exists(path):
		makedir(path)

def make_tree_once(path):
	global FSTree
	from libsaria.trees import FSTree
	global make_tree
	make_tree = make_tree_rest
	return make_tree(path)
def make_tree_rest(path):
	global FSTree
	tree = FSTree()
	for root,dirs,files in walk(path):
		split = root.split(sep)
		for file in files:
			tree.insert_path_split(split, file)
	return tree
make_tree = make_tree_once
