"""Subclass of GitView, which is generated by wxFormBuilder."""

import wx


from beatle import tran, model, localpath
from beatle.model import git
from beatle.lib import wxx
from beatle.lib.decorators import classproperty
from beatle.lib.handlers import Identifiers

from beatle.app import resources as rc
from beatle.app.ui.tools import clone_mnu
from beatle.app.ui.dlg import WorkingDialog
from beatle.app.ui.view import BaseView
from beatle.ctx import localcontext as context
from beatle.activity.git.ui import ui
from beatle.activity.git.ui import dlg as ui_dlg


# Implementing GitView
class GitView(BaseView, ui.GitView):
    """View pane for git repository"""
    perspective = ''
    clipboard_handler = False

    #command ids
    _editDelete = Identifiers.register("ID_DELETE")
    _openRepo = Identifiers.register("ID_OPEN_REPO")
    _newRepo = Identifiers.register("ID_NEW_REPO")
    _addItem = Identifiers.register("ID_ADD_ITEM")
    _stageItem = Identifiers.register("ID_STAGE_ITEM")
    _commitItem = Identifiers.register("ID_COMMIT_ITEM")
    _refreshRepo = Identifiers.register("ID_REFRES_REPO")
    _addRemote = Identifiers.register("ID_ADD_REMOTE")
    _pushRemote = Identifiers.register("ID_PUSH_REMOTE")


    def __init__(self, parent, root=None):
        """Initialize pane"""
        super(GitView, self).__init__(parent)
        self.frame = parent
        self.selected = None
        self.imglist = rc.GetBitmapImageList()
        self.m_tree.SetImageList(self.imglist)
        self.m_tree.AddRoot('Repositories')
        self._create_menus()
        self._bind_events()
        self._set_accelerators()
        # when we create a models view, we need to update elements
        if root is None:
            # reload full stack
            for wrk in context.app.workspaces:
                self.insert(wrk)
        else:
            self.insert(root)

    def insert(self, element):
        """Nested insert elements in tree"""
        if self.DoRenderAddElement(element):
            for cls in element._child:
                for k in element[cls]:
                    self.insert(k)

    def GetViewStatus(self):
        """Get working info about the view"""
        return str(self.m_tree.GetExpansionState())

    def SetViewStatus(self, status):
        """Set working info about the view"""
        try:
            l = eval(status)
            self.m_tree.SetExpansionState(l)
            return True
        except:
            return False


    @classproperty
    def name(cls):
        """returns the name of this view"""
        return 'Git'

    @classmethod
    def bitmap_index(cls):
        """return the bitmap index"""
        return rc.GetBitmapIndex('git')

    @classmethod
    def bitmap(cls):
        """return the bitmap"""
        return rc.GetBitmap('git')

    def _create_menus(self):
        """Create a custom menu entry in main menu"""
        self._menu = wxx.Menu(
            [self._newRepo, u"New repository", u"create new git repository", wx.ITEM_NORMAL, wx.ArtProvider.GetBitmap(wx.ART_NEW, wx.ART_MENU)],
            [self._openRepo, u"Open repository", u"open existing repository", wx.ITEM_NORMAL, wx.ArtProvider.GetBitmap(wx.ART_FILE_OPEN, wx.ART_MENU)],
            [],
            [self._addRemote, u"Add remote", u"add remote repository", wx.ITEM_NORMAL, wx.Bitmap(localpath("app/res/git_remote.xpm"), wx.BITMAP_TYPE_ANY)],
            [self._pushRemote, u"Push remote", u"push remote repository", wx.ITEM_NORMAL, wx.Bitmap(localpath("app/res/git_push.xpm"), wx.BITMAP_TYPE_ANY)],
            [],
            [self._addItem, u"Add to repository", u"add item to repository control", wx.ITEM_NORMAL],
            [self._stageItem, u"Stage item", u"stage item to repository control", wx.ITEM_NORMAL],
            [self._commitItem, u"Commit repository", u"commit changes to repository", wx.ITEM_NORMAL],
            [self._refreshRepo, u"Refresh", u"update repository status", wx.ITEM_NORMAL, rc.GetBitmap('reload')],
            )

        self.RegisterMenu('Git', self._menu)

    def _bind_events(self):
        """Binds events"""
        # Tree events
        self.m_tree.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnTreeSelChanged)
        self.m_tree.Bind(wx.EVT_RIGHT_DOWN, self.OnTreeMenu)

        self.BindSpecial(wx.EVT_UPDATE_UI, self.OnUpdateDelete, id=self._editDelete)
        self.BindSpecial(wx.EVT_MENU, self.OnDelete, id=self._editDelete)

        self.BindSpecial(wx.EVT_UPDATE_UI, self.OnUpdateNewRepository, id=self._newRepo)
        self.BindSpecial(wx.EVT_MENU, self.OnNewRepository, id=self._newRepo)

        self.
BindSpecial(wx.EVT_UPDATE_UI, self.OnUpdateOpenExistingRepository, id=self._openRepo)
        self.BindSpecial(wx.EVT_MENU, self.OnOpenExistingRepository, id=self._openRepo)

        self.BindSpecial(wx.EVT_UPDATE_UI, self.OnUpdateAddRemot
e, id=self._addRemote)
        self.BindSpecial(wx.EVT_MENU, self.OnAddRemote, id=self._addRemote)

        self.BindSpecial(wx.EVT_UPDATE_UI, self.OnUpdatePushRemote, id=self._pushRemote)
        self.BindSpecial(wx.EVT_MENU, self.OnPushRemote, id=self._pushRemote)

        self.BindSpecial(wx.EVT_UPDATE_UI, self.OnUpdateAddItemToRepository, id=self._addItem)
        self.BindSpecial(wx.EVT_MENU, self.OnAddItemToRepository, id=self._addItem)

        self.BindSpecial(wx.EVT_UPDATE_UI, self.OnUpdateStageItem, id=self._stageItem)
        self.BindSpecial(wx.EVT_MENU, self.OnStageItem, id=self._stageItem)

        self.BindSpecial(wx.EVT_UPDATE_UI, self.OnUpdateCommitRepository, id=self._commitItem)
        self.BindSpecial(wx.EVT_MENU, self.OnCommitRepository, id=self._commitItem)

        self.BindSpecial(wx.EVT_UPDATE_UI, self.OnUpdateRefreshStatus, id=self._refreshRepo)
        self.BindSpecial(wx.EVT_MENU, self.OnRefreshStatus, id=self._refreshRepo)

        super(GitView, self)._bind_events()

    def _set_accelerators(self):
        """Set the accelerator table"""
        # ctrl_alt = wx.ACCEL_CTRL + wx.ACCEL_ALT
        # ctrl_shf = wx.ACCEL_CTRL + wx.ACCEL_SHIFT
        aTable = wx.AcceleratorTable([
            wx.AcceleratorEntry(wx.ACCEL_NORMAL, wx.WXK_LEFT, BaseView._leftKeyId)
        ])
        self.SetAcceleratorTable(aTable)

    def DoRenderAddElement(self, obj):
        """Inserts element in tree"""
        # model tree
        treeOrder = [model.Workspace, git.GitRepo, git.GitRemotes,
            model.git.GitRemote, git.GitDir, git.GitFile]
        if type(obj) not in treeOrder:
            return False
        ti = treeOrder.index(type(obj))
        #check parent
        if self.m_tree.HoldsObject(obj.parent):
            p = obj.parent
        else:
            p = self.m_tree.GetRootItem()
        if obj.parent is not None:
            # find some major friend item with the same class
            tribal = obj.parent[type(obj)]
            index = tribal.index(obj)
            pre = None
            while index > 0 and pre is None:
                index = index - 1
                candidate = tribal[index]
                if not self.m_tree.HoldsObject(candidate):
                    continue
                pre = candidate
            if pre is not None:
                self.m_tree.InsertItem(p, pre, obj.label,
                    obj.bitmap_index, obj.bitmap_index, obj)
                if type(obj) is model.cc.Constructor:
                    self.m_tree.SetItemBold(obj, bold=obj.IsPreferred())
                elif type(obj) in [model.py.Module, model.py.Package]:
                    self.m_tree.SetItemBold(obj, bold=obj._entry)
                return True
        itemCount = 0
        citem, cookie = self.m_tree.GetFirstChild(p)
        if type(citem) is wx.TreeItemId:
            citem = self.m_tree.__fer__(citem)
        if type(citem) in treeOrder:
            if ti <= treeOrder.index(type(citem)):
                self.m_tree.PrependItem(p, obj.label,
                     obj.bitmap_index, obj.bitmap_index, obj)
                return True
        while type(citem) is not wx.TreeItemId or citem.IsOk():
            itemCount = itemCount + 1
            citem, cookie = self.m_tree.GetNextChild(p, cookie)
            if type(citem) not in treeOrder:
     