/*****************************************************************************
 * Copyright (C) 2004-2009 Christoph Thielecke <crissi99@gmx.de>             *
 *                                                                           *
 * 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 package 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 package; if not, write to the Free Software               *
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA *
 *****************************************************************************/

#ifndef KVPNCCONFIG_H
#define KVPNCCONFIG_H

#include <QList>
#include <QTextStream>
#include <QtCore/QFile>
#include <QtCore/QObject>
#include <QtCore/QPoint>
#include <QtCore/QSize>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtGui/QApplication>
#include <QtGui/QColor>

#include <kconfig.h>
#include <kstatusbar.h>
#include <kwallet.h>

#include "debugoutputtextedit.h"
#include "toolinfo.h"
#include "vpnaccountdata.h"

// ID for statusbar
#define ID_STATUS_MSG 1
#define ID_CONNECTION_MSG 2
#define ID_FLASH_MSG 3
	
namespace KVpncEnum
{
enum ConnectionStatus {
    disconnected = 0,
    connecting = 1,
    connected = 2
};

enum LogType {
    info = 0,
    remote = 1,
    error = 2,
    success = 3,
    debug = 4
};

enum HttpProxyAuthType {
	basic = 0,
	ntlm = 1
};

enum AuthenticationDirectionType {
	none = 0,
	zero = 1,
	one = 2
};
};

namespace OutputMsg
{
enum MsgType {
    normal = 0,
    error = 1,
    pty = 2
};
}

/**
 * This class holds global configuration data.
 */
class KVpncConfig : public QObject
{
    Q_OBJECT

public:
    KVpncConfig(QWidget *parent, KStatusBar *statusbar);
    ~KVpncConfig();

public:
    QString pathToVpnc;
    QString pathToCiscoVpnc;
    QString pathToRacoon;
    QString pathToRacoonctl;
    QString pathToSetkey;
    QString pathToIptables;
    QString pathToOpenssl;
    QString pathToIpsec;
    QString pathToPppd;
    QString pathToPptp;
    QString pathToL2tpd;
    QString pathToXl2tpd;
    QString pathToOpenl2tp;
    QString pathToKill;
    QString pathToKillall;
    QString pathToPing;
    QString pathToOpenvpn;
    QString pathToIp;
    QString pathToIfconfig;
    QString pathToRoute;
    QString pathToNetstat;
    QString pathToPkcs11Tool;
    QString pathToVtund;
    QString pathToCiscoCertMgr;
    QString pathToTail;
    QString pathToSsh;
    QString pathToKsshAskpass;
    QString pathToGnomeSshAskpass;
    QString AutoConnectProfile;
    QString RacoonDebugLevel;
    QString Vpnc_pid_file;
    QString Pppd_pid_file;
    QString lastProfile;
    QString logfileName;
    QString InterpreterShell;

    QString TmpPassword; //< from enter password dialog
    QString TmpGroupPassword; //< from enter password dialog
    QString TmpUsername; //< from enter password dialog
    QString TmpPrivKeyPassStr;
    QString TmpGatewayIP;
    QString TmpXauthInterPasscode; //< from Xauth interactive passcode dialog
    QString TmpPrivateKeyPass;
    QString TmpHttpProxyPassword;
	QString DnsDevice; //< device which the dns entry was added

    QString OldDefaultGw; //< default gw before connect
    QString OldDefaultDev; //< default gw dev before connect

    QString NewDefaultGw;
	
	QStringList PlutoDebug;
	QStringList KlipsDebug;

    bool minimizeAfterConnect;
    bool showDebugConsole;
    bool writeLogFile;
    bool useDefaultPaths;
    bool useSilentQuit;
    bool holdGeneratedScripts;
    bool programsInPath;
    bool enableDebugPppd;
    bool enableDebugPptpd;
    bool enableDebugL2tpd;
    bool enableDebugXl2tpd;
    bool enableDebugOpenl2tp;

    bool enableDebugXl2tpdNetwork;
    bool enableDebugXl2tpdpacket;
    bool enableDebugXl2tpdstate;
    bool enableDebugXl2tpdtunnel;

    bool enableFreeswanVerbose;
    bool enableDebugOpenvpn;
    bool useColorizedLogOutput;
    bool showInterfaceIPinTooltip;
    bool dontQuitOnCloseEvent;
    bool doAutoConnectAtStartup;
    bool useKwallet;
    bool showStatusBar;
    bool showToolBar;
    bool hideMainWindow;
    bool PppdDebugLevel;
    bool firstUseOfKwallet; //< for importing passwords if there are stored before
    bool shutdownIsCalled;
    bool haveUserData; //< flag if user data already collected, set after data is entered and unset if authretry
    bool skipKwalletStoring; //< true if save should skip saving into kwallet
    bool hideOnCloseInfo;
    bool feedbackMailSent;
    bool doKillL2tpdIfStillRunning; //< kill l2tpd if its still running and not started from kvpnc
    bool doKillXl2tpdIfStillRunning; //< kill xl2tpd if its still running and not started from kvpnc
    bool doKillRacoonIfStillRunning; //< kill racoon if its still running and not started from kvpnc
    bool showConnectionTimeInTooltip; //< True if the connection duration should be shown in kicker tooltip
    bool WaitingForXauth; //< if waiting for xauth is set to true, needed to detect wrong xautn data on strongswan

    bool OpenvpnNeedSecurityParameter;
	bool prefDlgOpen; //< if true prefDlgOpen is open

    int VpncDebugLevel;
    int KvpncDebugLevel;
    int OpenvpnDebugLevel;
    int PptpLogLevel;
    int PppdKernelLogLevel;
    int SshDebugLevel;
    int LogViewerFontSize;
    int mainwindow_pos_x;
    int mainwindow_pos_y;
    int mainwindow_height;
    int mainwindow_width;
    int connectSleepDelay; //< time beetween retry
    int connectSleepRetry; //< count of retries
    int tryConnectTimeout; //< timeout in at connecting
    int connectionStartTime;
    int runningCheckCounter;
    int runningCheckTimeout;
    int OpenvpnManagementPort;
    int AuthRetryCount; //< count of autn retry
    int maxConnectRetry; // max connect tries
    int currentConnectRetry;

    QList<ToolInfo *> *ToolList;
    QList<VpnAccountData *> *AccountList;
    VpnAccountData *currentProfile;

    QColor InfoLogColor;
    QColor RemoteLogColor;
    QColor ErrorLogColor;
    QColor SuccessLogColor;
    QColor DebugLogColor;
    QColor DebugBackgroundcolor;

    QApplication *appPointer;
    QPoint pos;
    KVpncEnum::ConnectionStatus status;
    QFile logfile;
    QTextStream logFileStream;
    DebugOutputTextEdit *LogOutput;
    KWallet::Wallet *wallet;
    KConfig* config; //< configuration data

    QPoint WindowPos;
    QSize WindowSize;

    struct IpsecImportSection {
        QString SectionName;
        QStringList SectionData;
    };
    
    struct PppdCapabilities {
		bool pppdHasMppeRequiredSupport;
		bool pppdHasRequireMppeSupport;
		bool pppdHasReplacedefaultrouteSupport;
		
		/* options for pppd depending on pppd version */
		
		// MPPE
		QString RequireMppeOption;
		QString Require128BitMppeOption;
		QString RefuseMppeOption;
		QString Refuse40BitMppeOption;
		QString Refuse128BitMppeOption;
		QString RequireStatelessOption;
		QString RequireStatefulOption;
		bool MppeOptionsInALine; // older pppd need all in one line
		
		// AUTH
		QString RequireAuthChapOption;
		QString RequireAuthMschapOption;
		QString RequireAuthMschapv2Option;
		QString RequireAuthPapOption;
		
		bool pppdHasMppeSupport; //< true if pppd has mppe support
		bool oldPppdStyle; //< true if old style was found ('mppe require')
		bool pppdOk; // if pppd could started
	};
	

    QList<VpnAccountData> *ImportedAccountList;
    struct PppdCapabilities pppdcap; //< pppd capabilities

    QWidget *parent;
    KStatusBar *statusbar;

    /**
     * Appends a log enty to debug console and log file
     * @param msg the text to append
     * @param type the type of the msg (info, debug, error, etc)
     */
    void appendLogEntry(QString msg, KVpncEnum::LogType type);

    /**
     *  Sets the output textedit for debug output
     * @param LogOutput
     */
    void setLogOutput(DebugOutputTextEdit *LogOutput);

    /**
    * save configuration
    */
    void saveOptions(bool saveOneProfile = false, QString Profile = "");

    /**
    * load configuration
    */
    void loadOptions();

    /**
    * check the value of the paths
    */
    void checkStandardPathValues();

    /**
     * collects the information of the external helper programs
     */
    void getToolsInfo();


    /**
     * removes a entry from configuration file
     * @param Name the entry which should be removed
     */
    void removeEntry(QString Name);

    VpnAccountData* findProfile(QList<VpnAccountData *> *list, const QString& Name);
    QString removeWhiteSpaceAtBegin(const QString);

    void slotStatusMsg(const QString &text, int id = ID_STATUS_MSG);
    void doBackupConfig();
    void restoreBackupConfig();

    bool exportKvpncConfig(QString filename);
    bool importKvpncConfig(QString filename, QString& RetName, bool& openProfileManager); //< true if profiles imported

    bool importIpsecConfig(QString filename, QString& RetName, bool& openProfileManager);
	bool importFritzboxConfig(QString filename, QString& Name, bool& openProfileManager);
};

#endif
