import os
import binascii
from git import Repo, Blob, Tree

def getLocalRepos(path):
    matches = []
    for root, dirnames, _ in os.walk(path):
        for dir in dirnames: 
            if dir == ".git":
                matches.append(root) 
    #some code for bare repositories 
    return matches


def getRepoDetals(path):

    repo = Repo(path)
    results = {'name':'', 'local_path':path, 'branches':[], 'remotes':[], 'active_branch':'master'}
    results['name'] = path[path.rindex(os.sep)+1:]
    results['active_branch'] = repo.active_branch.name
    for b in repo.branches:
        results['branches'].append(b.name)
    for r in repo.remotes:
        results['remotes'].append(r.name)    
    return results


def getFilesAndFoldersByTree(Tree):

    results = {'folders':[],'files':[]}

    results['folders'] = Tree.trees
    results['files'] = Tree.blobs

    #files = Tree.blobs
    #folders = Tree.trees
    #for entry in files: # intuitive iteration of tree members
    #        print(entry.path+" : "+str(entry))

    #for entry in folders: # intuitive iteration of tree members
    #        print("> "+entry.path+" : "+str(entry))
            #subfolders = entry.trees
            #print subfolders
            #subfiles = entry.blobs
            #print subfiles
    return results


def fetchRepo(path,branch):
    repo = Repo(path)

    RootTree = repo.heads[branch].commit.tree
    #RootTree = repo.tree()
    print "Root: "+ str(RootTree)
    firstLevel = getFilesAndFoldersByTree(RootTree)
    print firstLevel
    print "Second level"
    for folder in firstLevel['folders']:
        print getFilesAndFoldersByTree(folder)


def getContent(path,hash):
    #
    print str(Blob(Repo(path), binascii.a2b_hex(hash)).data_stream.read()) 
    pass

def getChilds(path,hash):
    #
    t = Tree(Repo(path), binascii.a2b_hex(hash),path="")
    return getFilesAndFoldersByTree(t)


#fetchRepo("/Users/lenchevsky/Projects/personal/organikos","master")
#print getRepoDetals("/Users/lenchevsky/Projects/personal/organikos")
#getContent("/Users/lenchevsky/Projects/personal/organikos","bf603e2414bce6f904da2675e8e9956ae47f3a14")
print getChilds("/Users/lenchevsky/Projects/personal/web_sites/lisa.ga","7a0e7db2abc56b4bdfd43a156f4b4a408a69012f")
