/* Copyright (c) 2008 Jeremy English <jhe@jeremyenglish.org>
*
* Permission to use, copy, modify, distribute, and sell this software and its
* documentation for any purpose is hereby granted without fee, provided that
* the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation.  No representations are made about the suitability of this
* software for any purpose.  It is provided "as is" without express or
* implied warranty.
*
* Created: 30-December-2008
*
* A test program for a slider gui element :)
*/

class Slider{
  private int x;
  private int y;
  private int w;
  private int h;
  private int value;
  private int sx; //slider x
  private int sy; //slider y
  private int sw; //slider width
  private int sh; //slider height;
  private color c;
  private boolean grabbed;
  private float stepper;
  
  //Value should be in the range of 0 to 100. 0 being all the way to the left.
  Slider(int x, int y, int width, int height, int value, color c){
    this.x = x;
    this.y = y;
    this.w = width;
    this.h = height;
    this.value = value;
    this.sw = round(width / 10);
    this.sh = height;
    this.sy = y;
    this.c = c;
    grabbed = false;
    stepper = (this.w - sw) / 100.0;
  }
  
  private void set_sx(){
    sx = round((value * stepper) + x);
//    print(wd);print(",");println(sx);    
  }
  
  void draw(){
    fill(0);
    //Paint the end peices
    rect(x,y,1,sh);
    rect(w + x,y,1,sh);
    
    //paint the slot for the slider
    rect(x,y + (h/2),w,1);
    
    //paint the slider
    fill(c);
    set_sx();
    rect(sx,sy,sw,sh);
  }
  
  void mousePress(){
    int mx = mouseX;
    int my = mouseY;
    grabbed = false;
    //Check to see if the mouse is inside the slider
    if (mousePressed && mouseButton == LEFT){
      //Check to see if the mouse is inside the slider
      if (sx < mx && mx < (sx + sw) && my > sy && my < (sy + sh)){
        grabbed = true;
      }
    }
  }
  
  void mouseDragged(){
    int mx = mouseX;
    if (grabbed){
      if(x <= mx && mx <= ((w - sw) + x)){
        int x1 = mx - x;
        println(x1);
        value = round(x1/stepper);
      }
    }
  }
  
  int getValue(){
    return value;
  }
  
}

Slider sl;
PFont font;

void setup(){
  size(200,200);
  sl = new Slider(20,100,160,20,100,color(0xff,0,0,75));
  background(0xFAF5C2);
  font = loadFont("ScalaSans-Caps-32.vlw");
}

void mousePressed(){
  sl.mousePress();
}

void mouseDragged(){
  sl.mouseDragged();
}

void draw(){
  colorMode(HSB,100,100,100);
  background(0xFAF5C2);
  sl.draw();
  fill(color(sl.getValue(), 100, 100));

  rect(20,20,25,25);
  rect(width - 20 - 25,20,25,25);

  textAlign(CENTER);
  textFont(font);
  String cap = "Value: " + sl.getValue();
  fill(color(0x20));
  text(cap,width/2,height - (height/10));
  
}
