use super::config::AccountConfig;
use super::Feedbin;
use crate::feed_api::{ApiMetadata, FeedApi, FeedApiErrorKind, FeedApiResult, Portal};
use crate::models::{LoginGUI, PasswordLoginGUI, PluginID, PluginIcon, PluginInfo, ServiceLicense, ServicePrice, ServiceType, Url, VectorIcon};
use failure::{Fail, ResultExt};
use feedbin_api::{ApiError as FeedbinApiError, ApiErrorKind as FeedbinApiErrorKind, FeedbinApi};
use parking_lot::RwLock;
use rust_embed::RustEmbed;
use std::path::PathBuf;
use std::str;
use std::sync::Arc;

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

pub struct FeedbinMetadata;

impl FeedbinMetadata {
    pub fn get_id() -> PluginID {
        PluginID::new("feedbin")
    }
}

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

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

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

        let login_gui = LoginGUI::Password(PasswordLoginGUI { url: true, http_auth: false });

        Ok(PluginInfo {
            id: self.id(),
            name: String::from("feedbin"),
            icon: Some(icon),
            icon_symbolic: Some(symbolic_icon),
            // It's impossible for this to fail to parse so the unwrap is safe
            website: Some(Url::parse("https://feedbin.com/").unwrap()),
            service_type: ServiceType::Remote { self_hosted: false },
            license_type: ServiceLicense::MIT,
            service_price: ServicePrice::Paid,
            login_gui,
        })
    }

    fn parse_error(&self, error: &dyn Fail) -> Option<String> {
        if let Some(error) = Fail::downcast_ref::<FeedbinApiError>(error) {
            match error.kind() {
                FeedbinApiErrorKind::InvalidLogin => return Some("Login failed".to_owned()),
                _ => (),
            };
        }
        None
    }

    fn get_instance(&self, path: &PathBuf, portal: Box<dyn Portal>) -> FeedApiResult<Box<dyn FeedApi>> {
        let account_config = AccountConfig::load(path).context(FeedApiErrorKind::Config)?;

        let mut api: Option<FeedbinApi> = None;

        if let Some(url) = account_config.get_url() {
            if let Ok(url) = Url::parse(&url) {
                if let Some(username) = account_config.get_user_name() {
                    if let Some(password) = account_config.get_password() {
                        api = Some(FeedbinApi::new(url.get(), username.clone(), password.clone()));
                    }
                }
            }
        }

        let feedbin = Feedbin {
            api,
            portal,
            logged_in: false,
            config: Arc::new(RwLock::new(account_config)),
        };
        let feedbin = Box::new(feedbin);
        Ok(feedbin)
    }
}
