

// classes referenced from superclass
//
//djl #include <qpe/fileselector.h>
//djl #include <qfile.h>
//djl #include <qdir.h>
//
#include <stdio.h>
//debug #include <stdlib.h>
//
#include "qtresistor.h"

/* 
 *  Constructs a View which is a child of 'parent', with the 
 *  name 'name' and widget flags set to 'f' 
 */
QtResistor::QtResistor( QWidget* parent,  const char* name, WFlags fl )
    : ResistorView(parent, name, fl)
{
    //tm4v = new ResistorView(parent, name, fl);
    resistance=resistanceTab1->text();
    voltage=voltageTab1->text();
    current=currentTab1->text();
    percentage=percentageTab1->text();
    if ( !name )
	setName( "Resistor Value Calculator" );
    //resize( 236, 299 ); 
    //
    // create the radio button effect
    calcFieldBtnGrp->insert((QButton*)voltageRBtn, 0 );
    calcFieldBtnGrp->insert((QButton*)currentRBtn, 1 );
    calcFieldBtnGrp->insert((QButton*)resistanceRBtn, 2 );
    calcBtnGrpSetDisable();

    // popup menu string labels for bands 1,2,3
    colorList[0] = "Black";
    colorList[1] = "Brown";
    colorList[2] = "Red";
    colorList[3] = "Orange";
    colorList[4] = "Yellow"; 
    colorList[5] = "Green";
    colorList[6] = "Blue";
    colorList[7] = "Violet";
    colorList[8] = "Gray";
    colorList[9] = "White";

    // popup menu string labels for band 4
    percentList[0] = "brown";
    percentList[1] = "red";
    percentList[2] = "green";
    percentList[3] = "blue";
    percentList[4] = "gold"; 
    percentList[5] = "silver";
    //percentList[6] = "none";

    colors[0].setRgb(11 ,11 ,11 ); // black
    colors[1].setRgb(165,42 ,42 ); // brown 
    colors[2].setRgb(238,11 ,11 ); // red
    colors[3].setRgb(238,154,0  ); // orange
    colors[4].setRgb(238,238,  0); // yellow
    colors[5].setRgb(11 ,238 ,11 ); // green
    colors[6].setRgb(11 ,11 ,238); // blue
    colors[7].setRgb(238,130,238); // violet
    colors[8].setRgb(190,190,190); // gray
    colors[9].setRgb(245,245,245); // white
    //
    // colors for 4th Band, START AT 10
    //
    colors[10].setRgb(165,42 ,42 ); // brown 
    colors[11].setRgb(238,11 ,11 ); // red
    colors[12].setRgb(11 ,238 ,11 ); // green
    colors[13].setRgb(11 ,11 ,238); // blue
    colors[14].setRgb(196,180, 85); // gold
    colors[15].setRgb(194 ,194,194); // silver
//    colors[15].setRgb(70 ,130,130); // silver
    colors[16].setRgb(194 ,184,84); // none/color of resistor

    band1 = new QPopupMenu( parent );
    band2 = new QPopupMenu( parent );
    band3 = new QPopupMenu( parent );
    band4 = new QPopupMenu( parent );

    //
    // popup menu Band1
    for( int i=0; i< 10; i++ )
        band1->setItemParameter(band1->insertItem(colorList[i], this, SLOT(slotMenu1(int)), 0, i),i);
    //
    // popup menu Band2
    for( int i=0; i< 10; i++ )
        band2->setItemParameter(band2->insertItem(colorList[i], this, SLOT(slotMenu2(int)), 0, i),i);
    //
    // popup menu Band3
    for( int i=0; i< 8; i++ )
        band3->setItemParameter(band3->insertItem(colorList[i], this, SLOT(slotMenu3(int)), 0, i),i);
    //
    // popup menu Band4
    for( int i=0; i< 6; i++ )
        band4->setItemParameter(band4->insertItem(percentList[i], this, SLOT(slotMenu4(int)), 0, i),i);

    // preset the color bands for 220 ohms 5%
    setBandColor( bandColorTxt_1, 2); // red
    setBandColor( bandColorTxt_2, 2); // red
    setBandColor( bandColorTxt_3, 1); // brown
    setBandColor( bandColorTxt_4, 4+10); // gold
}

/*  
 *  Destroys the object and frees any allocated resources
 */
QtResistor::~QtResistor()
{
    // no need to delete child widgets, Qt does it all for us
}

//SLOTS
void QtResistor::calcFromR()
{
    resistance = resistanceTab1->text();
    //FIX: show data was invalid and was corrected
    QPalette pal = resistanceTab1->palette() ;
    if( validateR( ) ) { // restore to default
        pal.setColor(QPalette::Disabled,QColorGroup::Text,colors[0]);//black
        pal.setColor(QPalette::Active,QColorGroup::Text,colors[9]);//white
    }
    else { // set to indicate corrections
        pal.setColor(QPalette::Disabled,QColorGroup::Text,colors[2]);//red
        pal.setColor(QPalette::Active,QColorGroup::Text,colors[2]);//red
    }
    resistanceTab1->setPalette(pal);
    //
    // update the GUI elements, calculate values, and update band colors
    resistanceTab1->setText(resistance);
    resistancePP_1->setText(resistance);
    calcTab1();
    bandUpdate(1);
}
void QtResistor::calcFromV()
{
    voltage = voltageTab1->text();
    //
    // check and fix invalid data entry (only trailing zeros
    int len = voltage.length();
    if( len < 1 ) {
        // INVALID, must be at least 1 digits of value
        // reset to default of 5 volts.
        voltage.sprintf("%d",5);
        voltageTab1->setText(voltage);
    }
    calcTab1();
}
void QtResistor::calcFromI()
{
    current = currentTab1->text();
    //
    // check and fix invalid data entry (only trailing zeros
    int len = current.length();
    if( len < 1 ) {
        // INVALID, must be at least 1 digits of value
        // reset to default of 5 volts.
        current.sprintf("%f",0.022727);
        currentTab1->setText(current);
    }
    calcTab1();
}
void QtResistor::calcFromPercent()
{
    percentage = percentageTab1->text();
    calcTab1();
    bandUpdate(4);
}

void QtResistor::calcTab1()
{
    bool ok;
    float r=0, v=0, i=0, p=0;
    QButton *selected = calcFieldBtnGrp->selected();
    if( (QRadioButton*)selected == currentRBtn ) {
      //
      // calc current from voltage and resistance
      //i=current.toFloat(&ok);
      r=resistance.toFloat(&ok);
      v=voltage.toFloat(&ok);
      i=v/r;
      current.sprintf("%f", i);
      currentTab1->setText(current);
      currentTab3->setText(current);
    }
    else if( (QRadioButton*)selected == voltageRBtn ) {
      //
      // calc voltage from current and resistance
      i=current.toFloat(&ok);
      r=resistance.toFloat(&ok);
      //v=voltage.toFloat(&ok);
      v=i*r;
      voltage.sprintf("%.3f", v);
      voltageTab1->setText(voltage);
    }
    else if( (QRadioButton*)selected == resistanceRBtn ) {
      //
      // calc resistance from current and voltage
      i=current.toFloat(&ok);
      //r=resistance.toFloat(&ok);
      v=voltage.toFloat(&ok);
      r=v/i;
      resistance.sprintf("%d", (int)r);
      //FIX: show data was invalid and was corrected
      QPalette pal = resistanceTab1->palette() ;
      if( validateR( ) ) { // restore to default
          pal.setColor(QPalette::Disabled,QColorGroup::Text,colors[0]);//black
          pal.setColor(QPalette::Active,QColorGroup::Text,colors[9]);//white
      }
      else { // set to indicate corrections
          pal.setColor(QPalette::Disabled,QColorGroup::Text,colors[2]);//red
          pal.setColor(QPalette::Active,QColorGroup::Text,colors[2]);//red
      }
      resistanceTab1->setPalette(pal);
      //
      // update the GUI elements, calculate values, and update band colors
      resistanceTab1->setText(resistance);
      resistancePP_1->setText(resistance);
      //
      // update the resistance bands with new data
      bandUpdate(1);
    }

    //
    // calc power
    p=i*v;
    power.sprintf("%f", p);
    powerTab3->setText(power);
}


void QtResistor::mousePressEvent( QMouseEvent *e )
{
    e = e; 
//debug     printf("x=%d, y=%d\n", e->x(), e->y());
}

void QtResistor::slotRaisePopupBand1()
{
    //band1->popup( bandBtn_1->mapToGlobal(QPoint(0,0) );
    //band1->popup( QPoint(bandBtn_1->pos().x(),0) );
    band1->popup( bandColorTxt_1->pos() );
}

void QtResistor::slotRaisePopupBand2()
{
    band2->popup( bandColorTxt_2->pos() );
}

void QtResistor::slotRaisePopupBand3()
{
    band3->popup( bandColorTxt_3->pos() );
}

void QtResistor::slotRaisePopupBand4()
{
    band4->popup( bandColorTxt_4->pos() );
}

//
// slots for Band popup menus
void QtResistor::slotMenu1(int id)
{
    QString update; update.sprintf("%d",id);
    resistance.replace(0,1,update);

    setBandColor( bandColorTxt_1, id);
    calcTab1();
}
void QtResistor::slotMenu2(int id)
{
    QString update; update.sprintf("%d",id);
    resistance.replace(1,1,update);

    setBandColor( bandColorTxt_2, id);
    calcTab1();
}
void QtResistor::slotMenu3(int id)
{
    QString zeros;
    for( int i=0; i<id; i++ )
      zeros.append("0");
    resistance.replace(2,100,zeros); // replace to the end of the string

    setBandColor( bandColorTxt_3, id);
    calcTab1();
}
void QtResistor::slotMenu4(int id)
{
    switch ( id ) {
      case 0:
      case 1:
        percentage.sprintf("%d",id+1);// 1-2%
        break; 
      case 2:
        percentage.sprintf(".%d",5); // .5%
        break; 
      case 3:
        percentage.sprintf(".%d",25); // .25%
        break; 
      case 4:
        percentage.sprintf("%d",5); // 5%
        break; 
      case 5:
        percentage.sprintf("%d",10); // 10%
        break; 
      default:
        percentage.sprintf("%d",5); // 5%
    }

    setBandColor( bandColorTxt_4, id+10); // offset id past band1,2,3 colors 
}

void QtResistor::setBandColor(QLabel *but, int id)
{
    QPalette pal = but->palette() ;
    pal.setColor(QPalette::Active,QColorGroup::Background,colors[id]);
    pal.setColor(QPalette::Active,QColorGroup::Foreground,colors[id]);
    pal.setColor(QPalette::Active,QColorGroup::Button,colors[id]);
    pal.setColor(QPalette::Active,QColorGroup::Base,colors[id]);
    pal.setColor(QPalette::Active,QColorGroup::Text,colors[id]);
    but->setPalette(pal);

    //
    // update display widgets
    resistanceTab1->setText(resistance);
    percentageTab1->setText(percentage);
    resistancePP_1->setText(resistance);
}

//
// calculate parallel resistance
void QtResistor::calcResistancePP( )
{
    float r1, r2, r3, r4, r5, r6;
    //
    // test and set all resistance values;
    r1 = resistancePP_1->text().toFloat();
    if( r1 > 0 ) r1 = 1/r1;
    r2 = resistancePP_2->text().toFloat();
    if( r2 > 0 ) r2 = 1/r2;
    r3 = resistancePP_3->text().toFloat();
    if( r3 > 0 ) r3 = 1/r3;
    r4 = resistancePP_4->text().toFloat();
    if( r4 > 0 ) r4 = 1/r4;
    r5 = resistancePP_5->text().toFloat();
    if( r5 > 0 ) r5 = 1/r5;
    r6 = resistancePP_6->text().toFloat();
    if( r6 > 0 ) r6 = 1/r6;
    //
    // calculate the results
    float total = (r1+r2+r3+r4+r5+r6);
    total = 1/total;
    //
    // post the results
    QString result;
    result.sprintf("%.3f",total);
    resistancePP_Result->setText( result );

}

//
// update the color bands 
void QtResistor::bandUpdate( int band )
{
    QLabel *colorBtn=bandColorTxt_1;
    int id=0;
    switch( band ) {
      case 1:
        //
        // band1
        id=resistance.mid(0,1).toInt();
        setBandColor( bandColorTxt_1, id); // offset id
        //
        // band2
        id=resistance.mid(1,1).toInt();
        setBandColor( bandColorTxt_2, id); // offset id
        //
        // band3
        id = resistance.length()-2;
        setBandColor( bandColorTxt_3, id); // offset id
        break;
      case 2:
        colorBtn = bandColorTxt_2;
        id=0;
        break;
      case 3:
        colorBtn = bandColorTxt_3;
        id=0;
        break;
      case 4:
        colorBtn = bandColorTxt_4;
        if( percentage == "1")
            id = 0;// percentage.sprintf("%d",id+1);// 1%
        else if( percentage == "2")
            id = 1;// percentage.sprintf("%d",id+1);// 2%
        else if( percentage == ".5")
            id = 2;// percentage.sprintf(".%d",5); // .5%
        else if( percentage == ".25")
            id = 3;// percentage.sprintf(".%d",25); // .25%
        else if( percentage == "5")
            id = 4;// percentage.sprintf("%d",5); // 5%
        else if( percentage == "10")
            id = 5;// percentage.sprintf("%d",10); // 10%
        else {
            id = 4;// percentage.sprintf("%d",5); // 5%
            percentage.sprintf("%d",5); // 5%
            percentageTab1->setText(percentage);
        }
        setBandColor( colorBtn, id+10); // offset id past band1,2,3 colors 
    }
}

void QtResistor::calcBtnGrpSetDisable()
{
    QButton *selected = calcFieldBtnGrp->selected();
    if( (QRadioButton*)selected == currentRBtn ) {
      //
      // enable / disable calculated input
      voltageTab1->setDisabled(FALSE);
      currentTab1->setDisabled(TRUE);
      resistanceTab1->setDisabled(FALSE);
      bandBtn_1->setDisabled(FALSE);
      bandBtn_2->setDisabled(FALSE);
      bandBtn_3->setDisabled(FALSE);
      bandBtn_4->setDisabled(FALSE);
    }
    else if( (QRadioButton*)selected == voltageRBtn ) {
      //
      // enable / disable calculated input
      voltageTab1->setDisabled(TRUE);
      currentTab1->setDisabled(FALSE);
      resistanceTab1->setDisabled(FALSE);
      bandBtn_1->setDisabled(FALSE);
      bandBtn_2->setDisabled(FALSE);
      bandBtn_3->setDisabled(FALSE);
      bandBtn_4->setDisabled(FALSE);
    }
    else if( (QRadioButton*)selected == resistanceRBtn ) {
      //
      // enable / disable calculated input
      voltageTab1->setDisabled(FALSE);
      currentTab1->setDisabled(FALSE);
      resistanceTab1->setDisabled(TRUE);
      bandBtn_1->setDisabled(TRUE);
      bandBtn_2->setDisabled(TRUE);
      bandBtn_3->setDisabled(TRUE);
      bandBtn_4->setDisabled(TRUE);
    }
}

//
// returns TRUE if validation was without issue/corrections
bool QtResistor::validateR( )
{
    bool retVal = TRUE;
    //
    // check and fix invalid data entry (only trailing zeros
    int len = resistance.length();
    if( len > 2 ) {
        //
        // test if trailing zeros are correct
        if( resistance.mid(2,len-2).toInt() > 0 ) {
            QString zeros;
            for( int i=0; i<len-2; i++ )
              zeros.append("0");
            resistance.replace(2,100,zeros); // replace to the end of the string
            retVal = FALSE;
        }
    }
    else if( len < 2 ) {
        // INVALID, must be at least 2 digits of value
        // reset to default of 220 ohm.
        resistance.sprintf("%d",220);
        retVal = FALSE;
    }
    return retVal;
}
