//! A basic example showing how to insert Events into a Timeseries using the
//! RustSDK
//! Expects an App with ID, provided by env var $DITTO_APP_ID, to be properly
//! configured in the Ditto Cloud.
//! Further a valid DITTO_LICENSE must also be available (also provided by an
//! env var). Both can be obtained from `https://portal.ditto.live`

#![allow(clippy::disallowed_macros)]
#![allow(deprecated)]

extern crate safer_ffi;

use std::{env, error::Error as ErrorTrait};

use chrono::Utc;
use dittolive_ditto::{identity::OnlinePlayground, prelude::*};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize, Debug)]
struct SensorEvent {
    cpu_temp: u8,
}

fn main() -> Result<(), Box<dyn ErrorTrait>> {
    let ditto = Ditto::builder()
        .with_temp_dir() // no need to store data locally
        .with_minimum_log_level(LogLevel::Debug)
        .with_identity(|ditto_root| {
            let auth_url = env::var("DITTO_AUTH_URL").ok();
            let app_id = AppId::from_env("DITTO_APP_ID")?;
            OnlinePlayground::new(
                ditto_root,
                app_id,
                String::from("92ef007e-8bb3-4ac2-a61a-30fe862240d9"),
                true,
                auth_url.as_deref(),
            )
        })?
        .with_transport_config(|_identity| {
            let mut transport_config = TransportConfig::new();
            if let Ok(sync_url) = env::var("DITTO_SYNC_URL") {
                transport_config.connect.websocket_urls.insert(sync_url);
            }
            transport_config
        })?
        .build()?;
    ditto.set_license_from_env("DITTO_LICENSE")?;
    ditto.sync().start()?;

    let store = ditto.store();
    #[allow(deprecated)]
    let ts = store.timeseries("readings").unwrap();
    let mut temp = 37;
    loop {
        let now = Utc::now();
        let msg = SensorEvent { cpu_temp: temp };
        #[allow(deprecated)]
        ts.insert(&now, msg).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(1000));
        temp += 1;
    }
}
