/*-
 * syslog-rs - a syslog client translated from libc to rust
 * 
 * Copyright 2025 Aleksandr Morozov
 * 
 * The syslog-rs crate can be redistributed and/or modified
 * under the terms of either of the following licenses:
 *
 *   1. the Mozilla Public License Version 2.0 (the “MPL”) OR
 *
 *   2. The MIT License (MIT)
 *                     
 *   3. EUROPEAN UNION PUBLIC LICENCE v. 1.2 EUPL © the European Union 2007, 2016
 */

use std::borrow::Cow;

use chrono::{Local, SecondsFormat};

use crate::{NEXTLINE, NILVALUE, SyslogMsgPriFac, WSPACE, truncate, truncate_n};

use super::{SyslogFormatted, SyslogFormatter};

#[derive(Debug, Clone)]
#[repr(transparent)]
pub struct FormatFile(Cow<'static, str>);

unsafe impl Send for FormatFile {}

impl From<String> for FormatFile
{
    fn from(value: String) -> FormatFile 
    {
        return Self(Cow::Owned(value));
    }
}

impl From<&'static str> for FormatFile
{
    fn from(value: &'static str) -> FormatFile
    {
        return Self(Cow::Borrowed(value));
    }
}

impl SyslogFormatter for FormatFile
{
    fn vsyslog1_format(&self, max_msg_size: usize, prifac: SyslogMsgPriFac, progname: &str, pid: Option<&str>) -> SyslogFormatted
    {
        let timedate = Local::now().to_rfc3339_opts(SecondsFormat::Secs, false);

        let msg_payload = truncate_n(&self.0, max_msg_size);

        let msg_payload_final = 
            if msg_payload.ends_with("\n") == true
            {
                truncate(msg_payload)
            }
            else
            {
                msg_payload
            };
           
        let msg_pkt = 
            [
                prifac.to_string().as_str(),
                WSPACE, timedate.as_str(), 
                WSPACE, progname,
                WSPACE, pid.map_or(NILVALUE, |f| f),
                WSPACE, msg_payload_final, NEXTLINE
            ]
            .concat();

        return 
            SyslogFormatted
            { 
                msg_header: None, 
                msg_payload: msg_pkt, 
                full_msg: None
            };
    }
}

