# Copyright (C) 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018  Rickard Lindberg, Roger Lindberg
#
# This file is part of Timeline.
#
# Timeline is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Timeline is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Timeline.  If not, see <http://www.gnu.org/licenses/>.


import wx


class NumCtrl(wx.Panel):

    def __init__(self, parent, size=(-1, -1)):
        wx.Panel.__init__(self, parent)
        self._CreateGui(size)
        self._text_befor_char_input = ''

    @property
    def numclass(self):
        return int

    def _CreateGui(self, size):
        sizer = wx.BoxSizer(wx.HORIZONTAL)
        self.text = wx.TextCtrl(self, size=size)
        self.spin = wx.SpinButton(self, style=wx.SP_VERTICAL, size=(-1, self.text.GetSize()[1] + 5))
        # 2147483647 is max allowed value to set and
        # -2147483648 is the minimum value allowed
        self.spin.SetMin(-2147483648)
        self.spin.SetMax(2147483647)
        sizer.Add(self.text, proportion=1, flag=wx.ALIGN_CENTER_VERTICAL)
        sizer.Add(self.spin, proportion=0, flag=wx.ALIGN_CENTER_VERTICAL)
        self.Bind(wx.EVT_TEXT, self._OnText, self.text)
        self.Bind(wx.EVT_SPIN_UP, self._OnSpinUp, self.spin)
        self.Bind(wx.EVT_SPIN_DOWN, self._OnSpinDown, self.spin)
        self.SetSizerAndFit(sizer)

    def SetValue(self, value):
        self.text.SetValue(value)
        self._text_befor_char_input = self.text.GetValue()

    def GetValue(self):
        return self.text.GetValue()

    def _OnText(self, event):
        pos = self.text.GetInsertionPoint()
        try:
            text = self.text.GetValue()
            if len(text) == 0:
                pass
            elif len(text) == 1:
                if text not in ' -+':
                    self.numclass(text)
            else:
                self.numclass(text)
        except ValueError:
            self.text.SetValue(self._text_befor_char_input)
            self.text.SetInsertionPoint(pos)
        self._text_befor_char_input = self.text.GetValue()
        event.Skip()

    def _OnSpinUp(self, event):
        self._Spin(1)
        event.Skip()

    def _OnSpinDown(self, event):
        self._Spin(-1)
        event.Skip()

    def _Spin(self, value):
        self.SetValue(str(self.numclass(self.GetValue()) + value))
