/* -*- mode: c++; tab-width: 4; c-basic-offset: 4 -*- */
/*
 * Copyright (C) 2005 Atmark <atmarkat _AT_ msn _DOT_ com>
 *                    AGAWA Koji <i _AT_ atty _DOT_ jp>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

#include <qcopchannel_qws.h>
#include <qpe/qcopenvelope_qws.h>
#include <qpe/qpeapplication.h>
#include "batteryplus.h"
#include "debug.h"

BatteryPlus& BatteryPlus::singleton()
{
	static BatteryPlus instance;

	return instance;
}

/*! \class BatteryPlus
  \brief BatteryPlusアプレットとのインターフェースを提供するクラスです。
 */
BatteryPlus::BatteryPlus(QObject *parent, const char *name)
	: QObject(parent, name),
	  isRunning_(false),
	  recvChannel_(NULL)
{
	if (QCopChannel::isRegistered("QPE/BatteryPlus"))
		isRunning_ = true;
	readConf();
}

BatteryPlus::~BatteryPlus()
{
	if (recvChannel_)
		delete recvChannel_;
}

void BatteryPlus::setMode(const QString& modeName)
{
	if (isRunning_) {
		QCopEnvelope e("QPE/BatteryPlus", "change(QString)");
		e << modeName;
	}
}

/*!
  QCopチャンネルにデータが送られてくるタイミングが不定なのが悩みどころ。
  例えばこのメソッドをpublicにして任意のタイミングで設定を読めるにしても
  このメソッドから返ってきた時点で処理が完了していることを保証出来ない。
  よってZPlayerの起動時に一回だけロードするようにしている。
  メインウィジェットが表示された時点でロードは完了している模様。
 */
void BatteryPlus::readConf()
{
	if (isRunning_) {
		recvChannel_ = new QCopChannel("QPE/BatteryRecv", this);
		connect(recvChannel_, SIGNAL(received(const QCString&, const QByteArray&)),
				this, SLOT(confEntryRecived(const QCString&, const QByteArray&)));
		QCopEnvelope e("QPE/BatteryPlus", "readConf()");
	}
}

void BatteryPlus::confEntryRecived(const QCString& msg, const QByteArray& data)
{
	QDataStream stream(data, IO_ReadOnly);

	if (msg == "freqMenu(QString)") {
		QString name;
		stream >> name;

		if (name == "MenuList")
			allModes_.clear();
		else
			allModes_.append(name);

		DPRINTF("freqMenu: %s", name.latin1());
	} else if (msg == "currentConf(QString)") {
		stream >> currentMode_;
		initialMode_ = currentMode_;
		DPRINTF("currentConf: %s", currentMode_.latin1());
	}
}
