/*
    This file is part of kenvy24 KDE multimedia utility
    Copyright (c) 2007  Valentin RUSU kenvy24@rusu.info

    This program 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 2 of the License or (at
    your option) version 3 or, at the discretion of KDE e.V. (which shall
    act as a proxy as in section 14 of the GPLv3), any later version.

    This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "vumeterimpl.h"
#include <functional>
#include <algorithm>
#include <kled.h>


struct TurnOffLed : public std::unary_function< KLed*, void > {
  void operator() ( KLed* led ) {
    led->off();
  }
};

const int  VuMeterImpl::dischargeRate = 160 / UPDATE_TIMER_INTERVAL;

VuMeterImpl::VuMeterImpl( QWidget* parent )  : QWidget( parent ), level(0) {
  initLeds();
}

VuMeterImpl::VuMeterImpl( QWidget* parent, const char* name )  : QWidget( parent ), level(0) {
  initLeds();
}

void VuMeterImpl::initLeds() {
  setupUi( this );

  dischargeStep = dischargeRate;

  leds.push_back(led0);
  leds.push_back(led1);
  leds.push_back(led2);
  leds.push_back(led3);
  leds.push_back(led4);
  leds.push_back(led5);
  leds.push_back(led6);
  leds.push_back(led7);
  leds.push_back(led8);
  leds.push_back(led9);
  leds.push_back(led10);
  leds.push_back(led11);
  leds.push_back(led12);
  leds.push_back(led13);
  leds.push_back(led14);
  leds.push_back(led15);
  leds.push_back(led16);
  leds.push_back(led17);
  leds.push_back(led18);
  leds.push_back(led19);
  leds.push_back(led20);

  std::for_each( leds.begin(), leds.end(), TurnOffLed() );
}

void VuMeterImpl::updateLevel(int newLevel) {
  int ledLevel = (newLevel * leds.size())/255;
  if ( ledLevel >= level ) {
    dischargeStep = dischargeRate;
    for (int i=level; i< ledLevel; i++){
      leds[i]->on();
    }
    level = ledLevel;
  }
}

void VuMeterImpl::resetLevel() {
}

void VuMeterImpl::timerTick() {
  if ( level > 0) {
    if ( dischargeStep == 0 ) {
      leds[level -1]->off();
      level--;
      dischargeStep = dischargeRate;
    }
    else {
      dischargeStep--;
    }
  }
}

void VuMeterImpl::turnOffLed( KLed*& )
{
}

#include "vumeterimpl.moc"
