import re
import os

from gitfs.filesystems.passthrough import PassthroughFuse, STATS

from .view import View


class CurrentView(View, PassthroughFuse):

    def __init__(self, *args, **kwargs):
        super(CurrentView, self).__init__(*args, **kwargs)
        self.root = self.repo_path
        self.dirty = set([])

    def rename(self, old, new):
        new = re.sub(self.regex, '', new)
        super(CurrentView, self).rename(old, new)

    def symlink(self, name, target):
        return os.symlink(target, self._full_path(name))

    def readlink(self, path):
        return os.readlink(self._full_path(path))

    def getattr(self, path, fh=None):
        full_path = self._full_path(path)
        st = os.lstat(full_path)

        attrs = dict((key, getattr(st, key)) for key in STATS)
        attrs.update({
            'st_uid': self.uid,
            'st_gid': self.gid,
        })

        return attrs

    def write(self, path, buf, offset, fh):
        result = super(CurrentView, self).write(path, buf, offset, fh)
        self.dirty.add(path)
        return result

    def release(self, path, fh):
        """
        Check for path if something was written to. If so, commit and push
        the changed to upstream.
        """

        if path in self.dirty:
            self.repo.index.add(os.path.split(path)[1])
            self.repo.commit("Update %s" % path, self.author, self.commiter)
            self.repo.push("origin", self.branch)
            self.dirty.remove(path)

        return os.close(fh)

@@ -283,16 +283,75 @@
 po_path%0A
+        # TODO: we need to store more here...create a dict%0A
         
@@ -1316,86 +1316,308 @@
     
-if path in self.dirty:%0A            self.repo.index.add(os.path.split(path)%5B1%5D)
+# TODO:add them into a queue and commit/push them in another thread%0A%0A        if path in self.dirty:%0A            clean_path = path%0A            if path.startswith(%22/%22):%0A                clean_path = path%5B1:%5D%0A%0A            self.repo.index.add(clean_path)%0A            # TODO: read commit message from dirty
 %0A   
@@ -1656,16 +1656,22 @@
 e %25s%22 %25 
+clean_
 path, se
@@ -1680,16 +1680,45 @@
 .author,
+%0A                            
  self.co
@@ -1775,16 +1775,17 @@
 branch)%0A
+%0A
         
@@ -1837,12 +1837,408 @@
 s.close(fh)%0A
+%0A    def mkdir(self, path, mode):%0A        result = super(CurrentView, self).mkdir(path, mode)%0A        path = %22/%25s/.keep%22 %25 os.path.split(path)%5B1%5D%0A        fh = self.create(path, 0644)%0A        self.release(path, fh)%0A        return result%0A%0A    def create(self, path, mode, fi=None):%0A        result = super(CurrentView, self).create(path, mode, fi)%0A        self.dirty.add(path)%0A        return result%0A

Fix #12: Very rudimentary way to create a directory..need more love