/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2026 metamuffin <metamuffin.org>
*/

use crate::request_info::RequestInfo;
use jellycommon::jellyobject::{ObjectBuffer, json::object_to_json};
use jellyui::render_view;
use rocket::response::{
    Responder,
    content::{RawHtml, RawJson},
};

pub enum UiResponse {
    Html(String),
    Json(String),
    Object(ObjectBuffer),
}

impl RequestInfo<'_> {
    pub fn respond_ui(&self, view: ObjectBuffer) -> UiResponse {
        if self.accept.is_json() || self.debug == "json" {
            let value = object_to_json(view.as_object());
            UiResponse::Json(serde_json::to_string(&value).unwrap())
        } else if self.debug == "raw" {
            UiResponse::Object(view)
        } else {
            UiResponse::Html(render_view(self.render_info(), view.as_object()))
        }
    }
}

impl<'r, 'o: 'r> Responder<'r, 'o> for UiResponse {
    fn respond_to(self, request: &'r rocket::Request<'_>) -> rocket::response::Result<'o> {
        match self {
            UiResponse::Html(x) => RawHtml(x).respond_to(request),
            UiResponse::Json(x) => RawJson(x).respond_to(request),
            UiResponse::Object(x) => x.to_bytes().respond_to(request),
        }
    }
}
