/*
 * 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 <kylin-ai/ai-engine/aiengine.h>
#include "matting_triton_client/client.h"
#include "ondevicevisioncapabilityengine.h"

namespace ai_engine::core_ai::vision {

void OndeviceVisionImageProcessEngine::setMattingResultCallback(
    ImageResultCallback callback) {
    mattingResultCallback_ = std::move(callback);

    if (mattingClient_ == nullptr) {
        return;
    }
}

result::AiEngineBaseResult
OndeviceVisionImageProcessEngine::mattingFromImageFile(
    const std::string &imageFilePath) {
    std::lock_guard<std::mutex> lock(MattingMutex_);
    MattingRunning_.store(true, std::memory_order_release);
    result::AiEngineBaseResult error;
    error.success = true;
    ImgBase64Result res = mattingClient_->MattingRequestByPath(imageFilePath);
    if (res.errorCode != -1) {
        error.success = false;
        error.error = ai_engine::EngineError(
            (int)VisionEngineErrorCode::ImageFileReadError,
            "[MattingTriton]: failed to Request Matting by img path.");
        MattingRunning_.store(false, std::memory_order_release);
        return error;
    }
    ImageResult result;
    result.success = true;
    result.imageFormat = res.format;
    result.imageBase64Data = res.base64Result;
    result.modelName = modelName_;
    if (MattingRunning_.load(std::memory_order_acquire) == true)
        mattingResultCallback_(result);
    MattingRunning_.store(false, std::memory_order_release);

    return error;
}

result::AiEngineBaseResult
OndeviceVisionImageProcessEngine::mattingFromBase64ImageData(
    const std::string &imageBase64Data) {
    std::lock_guard<std::mutex> lock(MattingMutex_);
    MattingRunning_.store(true, std::memory_order_release);
    result::AiEngineBaseResult error;
    error.success = true;
    ImgBase64Result res =
        mattingClient_->MattingRequestByBase64(imageBase64Data);
    if (res.errorCode != -1) {
        error.success = false;
        error.error = ai_engine::EngineError(
            (int)VisionEngineErrorCode::ImageFileReadError,
            "[MattingTriton]: failed to Request Matting by base64.");
        MattingRunning_.store(false, std::memory_order_release);
        return error;
    }
    ImageResult result;
    result.success = true;
    result.imageFormat = res.format;
    result.imageBase64Data = res.base64Result;
    result.modelName = modelName_;
    if (MattingRunning_.load(std::memory_order_acquire) == true)
        mattingResultCallback_(result);
    MattingRunning_.store(false, std::memory_order_release);

    return error;
}

result::AiEngineBaseResult
OndeviceVisionImageProcessEngine::initMattingsModule() {
    result::AiEngineBaseResult error;
    error.success = true;
#ifdef TRITON_CLIENT
    tc::Error err = mattingClient_->LoadModel();
    int errorCode = 0;

    if (err.Message() ==
        "explicit model load / unload is not allowed if polling is enabled")
        errorCode = (int)ai_engine::VisionEngineErrorCode::ModelEarlyLoaded;
    else if (err.Message() == "HTTP client failed: Couldn't connect to server")
        errorCode = (int)ai_engine::VisionEngineErrorCode::FileNotFound;
    if (!err.IsOk()) {
        error.error =
            ai_engine::EngineError((int)errorCode, err.Message().c_str());
        error.success = false;
        return error;
    }
#endif
    return error;
}

result::AiEngineBaseResult
OndeviceVisionImageProcessEngine::destroyMattingsModule() {
    result::AiEngineBaseResult error;
    error.success = true;
#ifdef TRITON_CLIENT
    tc::Error err = mattingClient_->RemoveModel();

    if (!err.IsOk()) {
        error.error = ai_engine::EngineError(
            (int)ai_engine::VisionEngineErrorCode::OcrModelError,
            err.Message().c_str());
        error.success = false;
        return error;
    }
#endif
    return error;
}

void OndeviceVisionImageProcessEngine::stopMattingProcess() {
    if (MattingRunning_.load(std::memory_order_acquire)) {
        MattingRunning_.store(false, std::memory_order_release);
        ImageResult result;
        result.success = true;
        result.imageFormat = "";
        result.imageBase64Data = "";
        result.modelName = modelName_;
        mattingResultCallback_(result);
    }
}

} // namespace ai_engine::core_ai::vision
