/********************************************************************************************
example 9 -- clocktime.cpp
    making military time into clocktime
********************************************************************************************/
#include "clocktime.h"
#include <iostream>
using namespace std;
//------- Initialize static class data -------
bool clocktime::AMPM = false;

//------- Enhanced Default Constructor -------
clocktime::clocktime(const int h, const int m, const int s) {
    hour=0;
    minute = 0;
    second = 0;

    addSecond(s);
    addMinute(m);
    addHour(h);
}

//------- Manage static class data -------
void clocktime::show24H(const bool& set) {
    AMPM = (!set);
}

void clocktime::showAMPM(const bool& set) {
    AMPM = set;
}

//------- Print the object in "pretty" format -------
void clocktime::print(ostream& out) const {
    if (AMPM) {
        if ((hour > 0) && (hour < 10))
            out << '0';
        if (hour == 0)
            out << 12;
        else if (hour > 12)
            out << hour - 12;
        else
        out << hour;
    }
    else {
        if (hour < 10)
            out << '0';
        out << hour;
    }
    out << ':';

    if (minute < 10)
        out << '0';
    out << minute << ':';
    if (second < 10)
        out << '0';
    out << second;

    if (AMPM) {
        if (hour < 12)
            out << " AM";
        else
            out << " PM";
    }
};

//------- "managed" addition functions -------
void clocktime::addHour(const int h) {
    int sum = hour + h;
    if (sum > -1)
        hour = sum % 24;
    else
        hour = (sum + 24) % 24;
}

void clocktime::addMinute(const int m) {
    int sum = minute + m;
    if (sum > -1) {
        addHour(sum / 60);
        minute = sum % 60;
    }
    else {
        addHour((sum - 60) / 60);
        minute = (sum + 60)% 60;
    }
}

void clocktime::addSecond(const int s) {
    int sum = second + s;
    int mag = s/60;
    if (sum > -1) {
        addMinute(sum/60);
        second = sum % 60;
    }
    else {
        addMinute((sum - 60) / 60);
        second = (sum + 60*(mag+1)) % 60;
    }
}

void clocktime::addSame(const clocktime& mt) {
    addHour(mt.hour);
    addMinute(mt.minute);
    addSecond(mt.second);
}

//------- user-defined operators -------
clocktime clocktime::operator+(const clocktime& mt) const {
    clocktime temp;
    temp.addSame(*this);
    temp.addSame(mt);
    return temp;
}

ostream& operator<<(ostream& out, const clocktime& mt) {
    mt.print(out);
    return out;
}