
//********************************//

void apply_scene(uint8_t new_scene, uint8_t light)
{
  if (new_scene == SCENE_RELEAX)
  {
    bri[light] = 144;
  } else if (new_scene == SCENE_BRIGHT)
  {
    bri[light] = 254;
  } else if (new_scene == SCENE_NIGHTLY)
  {
    bri[0] = 25;
    bri[1] = 0;
    bri[2] = 0;
    bri[3] = 0;
  }
}

//********************************//

void process_lightdata(uint8_t light, float tt)
{
  if (tt <= 0)
  {
    tt = default_transitiontime;
  }
  if (light_state[light])
  {
    step_level[light] = (bri[light] - current_bri[light]) / tt;

  } else {
    step_level[light] = current_bri[light] / tt;
  }
}

//********************************//

void lightEngine()
{

  if (millis() < (last_lightengine_activity + TIME_LIGHTENGINE_INTERVAL_MS)) {
    // abort processing, the transition setting is a delay of seconds
    return;
  }

  last_lightengine_activity = millis();

  for (int i = 0; i < LIGHTS_COUNT; i++)
  {

    if (light_state[i] == true)
    {
      if (bri[i] != current_bri[i])
      {
        in_transition = true;
        current_bri[i] += step_level[i] / BRI_MOD_STEPS_PER_SEC;

        if ((step_level[i] > 0.0 && current_bri[i] > bri[i]) ||
            (step_level[i] < 0.0 && current_bri[i] < bri[i]))
        {
          current_bri[i] = bri[i];
          //Serial.println("Reached target bri[" + (String)i + "] = " + (String)bri[i]);
        }

        current_pwm[i] = calcPWM(current_bri[i]);
        //Serial.println("lon: pin" + (String)i + " = PWM(" + (String)tmp_pwm + ")");
        analogWrite(pins[i], current_pwm[i]);
      }
    } else { // light state is off

      if (current_bri[i] != 0)
      {
        in_transition = true;
        current_bri[i] -= step_level[i] / BRI_MOD_STEPS_PER_SEC;

        if (current_bri[i] < 0)
        {
          current_bri[i] = 0;
          //Serial.println("Reached target bri[" + (String)i + "] = " + (String)bri[i]);
        }

        current_pwm[i] = calcPWM(current_bri[i]);
        //Serial.println("loff: pin" + (String)i + " = PWM(" + (String)tmp_pwm + ")");
        analogWrite(pins[i], current_pwm[i]);
      }
    }

  }  // for loop end

  if (in_transition)
  {
    delay(6);
    in_transition = false;
  }
}

//********************************//

uint16_t calcPWM(float tbri)
{
  uint16_t tmp_pwm = PWM_OFF;
  if (tbri > 0.0)
  {
    tmp_pwm = PWM_MIN + (int)(tbri * BRI_TO_PWM_FACTOR);
  }
  if (tmp_pwm > PWM_MAX) 
  {
    tmp_pwm = PWM_MAX;
  }

  return tmp_pwm;
}

//********************************//
