/*
 * 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 _CORE_VISION_SERVICE_PROXY_H_
#define _CORE_VISION_SERVICE_PROXY_H_

#include <functional>
#include <memory>
#include <string>

#include "_textrecognitionconfig.h"
#include "corevisionserviceglue.h"
#include "error.h"
#include "textrecognition.h"

namespace kyai {
namespace core {
namespace vision {

using ReconnectedCallback = std::function<void()>;

class CoreVisionServer {
public:
    static CoreVisionServer &getInstance();

    ~CoreVisionServer();

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

    GDBusConnection *getConnection() const { return connection_; }

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

private:
    GDBusConnection *connection_{nullptr};
};
class CoreVisionServiceProxy {
public:
    ~CoreVisionServiceProxy();

    bool connectToServer();
    bool reconnectServer();

    void setRecognitionResultCallback(TextRecognitionResultCallback callback,
                                      void *userData);
    void setReconnectedCallback(ReconnectedCallback callback);

    int initEngine(const char *config, int *sessionId);

    void destroyTextRecognition(int sessionId);

    void recognizeTextFromImageFileAsync(int sessionId, const char *imageFile);

    void recognizeTextFromImageDataAsync(int sessionId, const char *data,
                                         unsigned int imageDataLength);

private:
    static void onRecognitionResultCallback(GObject *sourceObject,
                                            GAsyncResult *res,
                                            gpointer userData);
    void handleErrorOccurred(int errorCode);
    void handleServerClosed();
    void handleServerTimeout();

private:
    TextRecognitionResultCallback recognitionCallback_{nullptr};
    ReconnectedCallback reconnectedCallback_{nullptr};
    void *recognitionUserData_{nullptr};

    AiRuntimeCoreVisionService *proxy_{nullptr};

    int reconnectAttempts_{0};
    static constexpr int maxReconnectAttempts{10};
};

}  // namespace vision
}  // namespace core
}  // namespace kyai
#endif
