#include "znc/main.h"
#include "znc/Modules.h"
#include "znc/User.h"
#include "znc/Nick.h"
#include "znc/Chan.h"
#include "znc/ZNCString.h"

class CPMLog : public CModule {
public:
    MODCONSTRUCTOR(CPMLog) {
      // TODO: Buffer size should be configurable
        m_Buffer.SetLineCount(500);
    }

    virtual ~CPMLog() {}

    virtual void OnClientLogin() {
      CString sBufLine;
      int i = 0;

      while (m_Buffer.GetLine(m_pUser->GetCurNick(), sBufLine, i++)) {
            PutUser(sBufLine);
	}
	//    m_Buffer.Clear();
    }

    virtual EModRet OnPrivMsg(CNick& Nick, CString& sMessage) {
        char szTimestamp[1024];
        time_t tm;
        time(&tm);
        // TODO: Timestamp should be optional
        // TODO: Timezone offset needs calculating
        // TODO: Correctly ignore internal ZRC chat
        strftime(szTimestamp, sizeof(szTimestamp), "[%m/%d %H:%M:%S]", localtime(&tm));

        m_Buffer.AddLine(":" + GetModNick() + "!" + GetModName() + "@znc.in PRIVMSG ",
       			 " :" + (CString)szTimestamp + " <<" + Nick.GetNick() + ": " + sMessage);

	return CONTINUE;
    }

    virtual EModRet OnUserMsg(CString& Target, CString& sMessage) {
      char szTimestamp[1024];
      time_t tm;
      time(&tm);
      // TODO: As for OnPrivMsg
      strftime(szTimestamp, sizeof(szTimestamp), "[%m/%d %H:%M:%S]", localtime(&tm));

      // TODO: Rebroadcast outbound messages, don't just log, so all connected clients see them
      // TODO: This is not the correct way to call AddLine
      if (Target[0] != '#') {
          m_Buffer.AddLine(":" + GetModNick() + "!" + GetModName() + "@znc.in PRIVMSG ",
			   " :" + (CString)szTimestamp + " " + Target + ">>: " + sMessage);
        }

        return CONTINUE;
    }

  CBuffer m_Buffer;
    };

template<> void TModInfo<CPMLog>(CModInfo& Info) {
Info.SetWikiPage("pmlog");
}

MODULEDEFS(CPMLog, "Logs all Private Messages, even if ZNC thinks you are online")

