/*
 * Copyright (C) 2022  Aravinth Manivannan <realaravinth@batsense.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero 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 Affero General Public License for more details.
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
//! App data: database connections, etc.
use std::sync::Arc;

use libconductor::Conductor;

//use crate::errors::ServiceResult;
use crate::settings::{ConductorType, Settings};

/// App data
pub struct Ctx {
    //    /// database ops defined by db crates
    //    pub db: BoxDB,
    /// app settings
    pub settings: Settings,
    pub source_code: String,
    pub conductor: Arc<Box<dyn Conductor>>,
}

impl Ctx {
    #[cfg(not(tarpaulin_include))]
    /// create new instance of app data
    pub async fn new(s: &Settings) -> ArcCtx {
        let source_code = {
            let mut url = s.source_code.clone();
            url = url.join("tree/").unwrap();
            url = url.join(crate::GIT_COMMIT_HASH).unwrap();
            url.into()
        };

        let conductor: Box<dyn Conductor> = match s.conductor {
            ConductorType::Dummy => {
                use dummy_conductor::DummyConductor;

                Box::new(DummyConductor {})
            }
        };

        let conductor = Arc::new(conductor);

        let data = Ctx {
            //   db,
            settings: s.clone(),
            source_code,
            conductor,
        };

        Arc::new(data)
    }
}

pub type ArcCtx = Arc<Ctx>;
