use super::LocalRSS;
use super::cache::LocalRSSCache;
use crate::feed_api::{ApiMetadata, FeedApi, FeedApiError, FeedApiResult, Portal};
use crate::models::{ApiSecret, LoginGUI, PluginID, PluginIcon, PluginInfo, ServiceLicense, ServicePrice, ServiceType, VectorIcon};
use rust_embed::RustEmbed;
use std::path::Path;
use std::str;
use std::sync::Arc;
use tokio::sync::RwLock;

#[derive(RustEmbed)]
#[folder = "src/feed_api_implementations/local/icons"]
struct LocalResources;

pub struct LocalMetadata;

impl LocalMetadata {
    pub fn get_id() -> PluginID {
        PluginID::new("local_rss")
    }
}

impl ApiMetadata for LocalMetadata {
    fn id(&self) -> PluginID {
        Self::get_id()
    }

    fn info(&self) -> FeedApiResult<PluginInfo> {
        let icon_data = LocalResources::get("feed-service-local.svg").ok_or(FeedApiError::Resource)?;
        let icon = VectorIcon {
            data: icon_data.data.to_vec(),
            width: 48,
            height: 48,
        };
        let icon = PluginIcon::Vector(icon);

        let symbolic_icon_data = LocalResources::get("feed-service-local-symbolic.svg").ok_or(FeedApiError::Resource)?;
        let symbolic_icon = VectorIcon {
            data: symbolic_icon_data.data.to_vec(),
            width: 48,
            height: 48,
        };
        let symbolic_icon = PluginIcon::Vector(symbolic_icon);

        let login_gui = LoginGUI::None;

        Ok(PluginInfo {
            id: self.id(),
            name: String::from("Local RSS"),
            icon: Some(icon),
            icon_symbolic: Some(symbolic_icon),
            website: None,
            service_type: ServiceType::Local,
            license_type: ServiceLicense::GPLv3,
            service_price: ServicePrice::Free,
            login_gui,
        })
    }

    fn get_instance(&self, config_dir: &Path, portal: Box<dyn Portal>, _user_api_secret: Option<ApiSecret>) -> FeedApiResult<Box<dyn FeedApi>> {
        let cache = LocalRSSCache::load(config_dir)?;

        let local_rss = LocalRSS {
            portal: Arc::new(portal),
            cache: Arc::new(RwLock::new(cache)),
        };
        let local_rss = Box::new(local_rss);
        Ok(local_rss)
    }
}
