/*
 * 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/>.
 */

#include "_genaiimagesession.h"

namespace kylin {
namespace genai {
namespace vision {

_GenAiImageSession::_GenAiImageSession() {
    serviceProxy_.setReconnectedCallback([this] {
        initSession();
        if (imageConfig_) {
            serviceProxy_.setImageConfig(sessionId_,
                                         imageConfigToJson(*imageConfig_));
        }
    });
}

int _GenAiImageSession::init() {
    if (!initServer()) {
        return AiSdkCommonErrorCode::AISDK_RUNTIME_ERROR;
    }

    return initSession();
}

void _GenAiImageSession::setImageConfig(_ImageConfig *config) {
    imageConfig_ = config;
    serviceProxy_.setImageConfig(sessionId_, imageConfigToJson(*config));
}

void _GenAiImageSession::setImageResultCallback(
    VisionImageResultCallback callback, void *userData) {
    serviceProxy_.setImageResultCallback(callback, userData);
}

const char **_GenAiImageSession::getSupportedImageStyle(int *number) {
    return serviceProxy_.getSupportedImageStyle(sessionId_, number);
}

const ImageSize *_GenAiImageSession::getSupportedImageSize(int *number) {
    return serviceProxy_.getSupportedImageSize(sessionId_, number);
}

const int _GenAiImageSession::getSupportedImageNumber() {
    return serviceProxy_.getSupportedImageNumber(sessionId_);
}

void _GenAiImageSession::generateImageAsync(const char *prompt) {
    serviceProxy_.generateImageAsync(sessionId_, prompt);
}

bool _GenAiImageSession::initServer() {
    if (!serviceProxy_.connectToServer()) {
        return serviceProxy_.reconnectServer();
    }
    return true;
}

int _GenAiImageSession::initSession() {
    return serviceProxy_.initEngine(&sessionId_);
}

}  // namespace vision
}  // namespace genai
}  // namespace kylin
