/*
 * Copyright 2024 KylinSoft Co., Ltd.
 *
 * 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 3 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, see <https://www.gnu.org/licenses/>.
 */

#ifndef _GENAI_VISION_SERVICE_PROXY_H_
#define _GENAI_VISION_SERVICE_PROXY_H_

#include <jsoncpp/json/json.h>
#include <jsoncpp/json/value.h>

#include <functional>
#include <mutex>
#include <string>
#include <vector>

#include "error.h"
#include "genaivisionserviceglue.h"
#include "imageresult.h"

namespace kylin {
namespace genai {
namespace vision {

using ReconnectedCallback = std::function<void()>;
class GenAiVisionServer {
public:
    static GenAiVisionServer &getInstance();

    ~GenAiVisionServer();

    void init();
    bool available() const { return connection_ != nullptr; }

    GDBusConnection *getConnection() const { return connection_; }

private:
    void init(const std::string &unixPath);
    void destroy();

private:
    GDBusConnection *connection_{nullptr};
    mutable std::mutex mutex_;
};

class GenAiVisionServiceProxy {
public:
    ~GenAiVisionServiceProxy();
    bool connectToServer();
    bool reconnectServer();

    void setImageResultCallback(VisionImageResultCallback callback,
                                void *userData);
    void setReconnectedCallback(const ReconnectedCallback &callback);

    int initEngine(int *sessionId);
    void setImageConfig(int sessionId, const std::string &config);

    const char **getSupportedImageStyle(int sessionId, int *number);
    const ImageSize *getSupportedImageSize(int sessionId, int *number);
    const int getSupportedImageNumber(int sessionId);

    void generateImageAsync(int sessionId, const char *prompt);

private:
    void connectImageResultSignals(int sessionId);

    static void onImageResult(GDBusConnection *connection,
                              const gchar *senderName, const gchar *objectPath,
                              const gchar *interfaceName,
                              const gchar *signalName, GVariant *parameters,
                              gpointer userData);

    static void onImageGenerationFinishedCallback(GObject *sourceObject,
                                                  GAsyncResult *res,
                                                  gpointer userData);
    void stopImageGeneration();
    void handleErrorOccurred(int errorCode);
    void handleServerClosed();
    void handleResultTimeout();
    void handleGeneralError();

    bool parseJson(const std::string &params, Json::Value &root) const;
    std::vector<std::string> getImageStyleArryFromJsonString(
        const std::string &params);
    std::vector<ImageSize> getImageSizeArryFromJsonString(
        const std::string &params) const;

private:
    VisionImageResultCallback visionImageResultCallback_{nullptr};
    ReconnectedCallback reconnectedCallback_{nullptr};
    void *visionImageResultUserData_{nullptr};

    AiRuntimeGenAiVisionService *proxy_{nullptr};
    GenAiVisionServer *genaiVisionServer_{nullptr};

    const char **stylesArray_{nullptr};
    ImageSize *sizesArray_{nullptr};

    int currentSessionId_{0};
    bool isStopped_{false};

    guint timeoutId_{0};
    int reconnectAttempts_{0};
    static constexpr int maxReconnectAttempts = 10;
};

}  // namespace vision
}  // namespace genai
}  // namespace kylin
#endif
