import javax.swing.JFileChooser

class GriffonFlubberController {

    // these will be injected by Griffon
    def model
    def view

    def clearButtonMouseReleased = {
        model.flubText = ''
        //model.flubPointsTextArea.text = ''
        model.labelNo = 0
        model.timeLabel.text = '0:00'
    }

    def stopButtonMouseReleased = {
        if (model.timer != null) {
            model.timer.cancel();
            model.startTime = 0L;
        }
    }

    def flubButtonMouseReleased = {
        model.labelNo++;
        addLabel(Integer.toString(model.labelNo));
    }

    def saveButtonMouseReleased = {
        def chooser = app.builders.root.fileChooser();
        int rVal = chooser.showSaveDialog(view.containingWindows[0])
        if (rVal == JFileChooser.APPROVE_OPTION) {
            def outputFile = chooser.getSelectedFile()
            try {
                outputFile.write(model.flubText)
            } catch (IOException ex) {
                ex.printStackTrace()
            }
        }
    }

    def startButtonMouseReleased = {evt ->
        if (model.startTime == 0L) {
            model.startTime = System.currentTimeMillis();
            model.timer = new Timer()
            model.timer.schedule(new GroovyTimerTask(closure), 200, 200);
        }
    }
    
   

    String centerObject(w) {
    	def frame = view.containingWindows[0]
        def width = (frame.getWidth() - w) / 2
        return width.toString()
    }
    
    public void addLabel(String label) {
        def seconds = 0.0d
        if (model.startTime > 0L) {
            def millis = System.currentTimeMillis() - model.startTime
            seconds = (double) millis / 1000
        }

        model.flubText += "${seconds}\t${seconds}\t${label}\n"
    } 
    
	def closure = { 
            long millis = System.currentTimeMillis() - model.startTime
            int seconds = (int) (millis / 1000)
            int minutes = seconds / 60
            seconds = seconds % 60
            model.timeLabel.setText(String.format("%d:%02d", minutes, seconds))
            view.timePanel.repaint()
    }
}
