# Copyright (C) 2010, Daniel Popowich <danielpopowich@gmail.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# for desktop
import pyjd
# ui imports
from pyjamas.ui.HTML import HTML
from pyjamas.ui.RootPanel import RootPanel
from pyjamas.ui.Button import Button
from pyjamas.ui.DialogBox import DialogBox
from pyjamas.ui.Grid import Grid
from pyjamas.ui.HorizontalSlider import HorizontalSlider
from pyjamas.ui.Label import Label
from pyjamas.ui.HorizontalPanel import HorizontalPanel
from pyjamas.ui.SimplePanel import SimplePanel
from pyjamas.ui.CaptionPanel import CaptionPanel

# other pyjamas imports
from pyjamas import DOM

# pyjamas client-side library
from random import random
from datetime import datetime

# Timer class
from pyjamas.Timer import Timer

######################################################################
# The next three classes demonstrate three ways to create/use timers
######################################################################

class Clock:

    # pyjamas doesn't generate __doc__
    __doc__ = '''This demonstrates using Timer instantiated with the
    notify keyword, as in:<pre> timer = Timer(notify=func) </pre>When
    the timer fires it will call func() with no arguments (or
    <code>self</code> if it is a bound method as in this example).
    This timer is scheduled with the <code>scheduleRepeating()</code>
    method, so after func() is called, it is automatically rescheduled
    to fire again after the specified period.  The timer can be
    cancelled by calling the <code>cancel()</code> method; this
    happens when you click on the button.
    '''

    
    start_txt = 'Click to start the clock'
    stop_txt = 'Click to stop the clock'
    
    def __init__(self):

        # the button
        self.button = Button(listener=self)
        # set an attr on the button to keep track of its state
        self.button.stop = False
        # date label
        self.datelabel = Label(StyleName='clock')
        # the timer
        self.timer = Timer(notify=self.updateclock)
        # kick start
        self.onClick(self.button)

    def onClick(self, button):
        if self.button.stop:
            # we're stopping the clock
            self.button.stop = False
            self.timer.cancel()
            self.button.setText(self.start_txt)
        else:
            # we're starting the clock
            self.button.stop = True
            self.timer.scheduleRepeating(1000)
            self.button.setText(self.stop_txt)

    def updateclock(self, timer):

        # the callable attached to the timer with notify
        dt = datetime.now().replace(microsecond=0)
        self.datelabel.setText(dt.isoformat(' '))

class PopupTimerButton(Timer, Button):

    __doc__ = '''The timer in this demo is a subclass of Timer which
    implements the <code>run()</code> method.  Worth noting in this
    example is the use of the method <code>schedule()</code> at the
    end of <code>run()</code> (contrast this to the use of
    <code>scheduleRepeating()</code> in the previous example).  In this
    demo when the timer counts down to zero it creates a popup which
    will appear in the box to the left.  The timer can be cancelled by
    clicking the button before it reaches zero.
    '''

    def __init__(self, countdown):
        # It's a Timer, no it's a Button, WAIT!  It's BOTH!!
        Timer.__init__(self)
        Button.__init__(self)

        # save the countdown value
        self.countdown_save = countdown
        # this instance handles the clicks
        self.addClickListener(self)
        # the box the popups go into
        self.box = SimplePanel(StyleName='popupbox')
        # kickstart
        self.reset()

    def run(self):

        # When subclassing, we just implement the run method

        # update the countdown
        self.setHTML('Popup in <b>%d</b> seconds! (Click to cancel)'
                     % self.countdown)
        # reschdule if we're not to zero else create the popup
        self.countdown -= 1
        if self.countdown >= 0:
            self.schedule(1000)
        else:
            self.create_popup()
            self.reset()
    
    def reset(self):
        # reset to starting state
        self.setHTML('Click for countdown popup')
        self.countdown = self.countdown_save
        self.start = True

    def onClick(self, *arg):

        # handle button clicks

        # are we cancelling?
        if not self.start:
            self.cancel()
            self.reset()
            return

        # no we're starting
        self.start = False
        self.schedule(1)

    def create_popup(self):

        # create the popup in the middle box
        popup = DialogBox(False, False)
        popup.onClick = lambda w: popup.hide()
        popup.setHTML('<b>Hello!</b>')
        popup.setWidget(Button('Close', popup))
        x = self.box.getAbsoluteLeft() + random()*100
        y = self.box.getAbsoluteTop() + random()*100
        popup.setPopupPosition(x, y)
        popup.show()

class RandomColor:

    __doc__ = '''This last example demonstrates what most pyjamas
    programmers currently do with timers: create a Timer instance
    specifying <code>notify</code> with an object that has an
    <code>onTimer</code> attribute that is callable.  The slider on
    the left will adjust how often the middle panel changes color; it
    is either OFF or a value of seconds from 1 to 5.  Changing the
    slider immediately cancels the current timer and starts a new
    timer to change the color in the newly specified time.  Like the
    previous example, this timer reschedules itself (if it wasn't
    turned off) at the end of the call to <code>onTimer()</code>.
    '''

    def __init__(self):

        # create the label and slider
        self.__label = Label('OFF')