#include "Television.h"
using namespace std;

//=======================================================================
// Please gloss over the details of this section.
// 
// The code provides a convenient utility to generically convert
// objects to their string representation, but I don't want to explain
// how it works at this point in time.

#include <sstream>                              // DONT ASK
template<class T>
string ToString(const T& val) {
  stringstream strm;
  strm << val;
  return strm.str();
}

//=======================================================================


Television::Television() {
  powerOn = false;
  muted = false;
  volume = 5;
  channel = 2;
  prevChan = 2;

  minVolume=0;
  maxVolume = 10;
  minChannel = 2;
  maxChannel = 99;
}

Television::toggleMute() {
  if (powerOn)
    muted = !muted;
}


int Television::volumeUp() {
  if (powerOn) {
    if (volume < maxVolume)
      volume++;
    muted = false;
    return volume;
  } else
    return -1;
}
        
int Television::volumeDown() {
  if (powerOn) {
    if (volume > minVolume)
      volume--;
    muted = false;
    return volume;
  } else
    return -1;
}
        
int Television::channelUp() {
  if (powerOn) {
    prevChan = channel;
    channel++;
    if (channel > maxChannel)
      channel = minChannel;    // wrap around
    return channel;
  } else
    return -1;
}

int Television::channelDown() {
  if powerOn {
    prevChan = channel;
    channel--;
    if (channel < minChannel)
      channel = maxChannel;     // wrap around
    return channel;
  } else
    return -1;
}

bool Television::setChannel(int number) {
  if ((powerOn) && (minChannel <= number) && (number <= maxChannel)) {
      prevChan = channel;      // must record this before it is lost
      channel = number;
      return true;
  } else
    return false;
}      


int Television::jumpPrevChannel() const {
  if (powerOn) {
    int temp;
    temp = channel;
    channel = prevChan;
    prevChan = temp;
    return channel;
  } else
    return -1;
}


string Television::toString() const {
  string display;
  string powerstring = (powerOn ? "true" : "false");
  display = "Power setting is currently " + powerstring + "\n";
  display += "Channel setting is currently "+ ToString(channel) + "\n";
  display += "Volume setting is currently "+ ToString(volume) + "\n";
  string mutestring = (muted ? "true" : "false");
  display += "Mute is currently " + mutestring;
  return display;
}


std::ostream& operator<<(std::ostream& out, const Television& tv) {
  out << tv.toString();
  return out;
}
