use crate::feed_api::{FeedApi, FeedApiError};
use crate::models::{ArticleID, CategoryID, FatArticle, FeedID, FeedMapping, Marked, Read, SyncResult, TagID, Tagging};
use reqwest::Client;
use std::collections::HashSet;
use tokio::sync::RwLock;

pub struct ActionCache {
    articles_marked_read: HashSet<ArticleID>,
    articles_marked_unread: HashSet<ArticleID>,
    articles_marked: HashSet<ArticleID>,
    articles_unmarked: HashSet<ArticleID>,
    articles_tag_added: HashSet<Tagging>,
    articles_tag_removed: HashSet<Tagging>,
    feeds_marked_read: HashSet<FeedID>,
    categories_marked_read: HashSet<CategoryID>,
    tags_marked_read: HashSet<TagID>,
}

impl ActionCache {
    pub fn new() -> Self {
        ActionCache {
            articles_marked_read: HashSet::new(),
            articles_marked_unread: HashSet::new(),
            articles_marked: HashSet::new(),
            articles_unmarked: HashSet::new(),
            articles_tag_added: HashSet::new(),
            articles_tag_removed: HashSet::new(),
            feeds_marked_read: HashSet::new(),
            categories_marked_read: HashSet::new(),
            tags_marked_read: HashSet::new(),
        }
    }

    pub fn add_article_marked_read(&mut self, id: &ArticleID) {
        if self.articles_marked_unread.contains(id) {
            self.articles_marked_unread.remove(id);
        } else {
            self.articles_marked_read.insert(id.clone());
        }
    }

    pub fn add_article_marked_unread(&mut self, id: &ArticleID) {
        if self.articles_marked_read.contains(id) {
            self.articles_marked_read.remove(id);
        } else {
            self.articles_marked_unread.insert(id.clone());
        }
    }

    pub fn add_article_mark(&mut self, id: &ArticleID) {
        if self.articles_unmarked.contains(id) {
            self.articles_unmarked.remove(id);
        } else {
            self.articles_marked.insert(id.clone());
        }
    }

    pub fn add_article_unmark(&mut self, id: &ArticleID) {
        if self.articles_marked.contains(id) {
            self.articles_marked.remove(id);
        } else {
            self.articles_unmarked.insert(id.clone());
        }
    }

    pub fn add_article_tagged(&mut self, article_id: &ArticleID, tag_id: &TagID) {
        let tag_article_model = Tagging {
            article_id: article_id.clone(),
            tag_id: tag_id.clone(),
        };
        if self.articles_tag_removed.contains(&tag_article_model) {
            self.articles_tag_removed.remove(&tag_article_model);
        } else {
            self.articles_tag_added.insert(tag_article_model);
        }
    }

    pub fn add_article_untagged(&mut self, article_id: &ArticleID, tag_id: &TagID) {
        let tag_article_model = Tagging {
            article_id: article_id.clone(),
            tag_id: tag_id.clone(),
        };
        if self.articles_tag_added.contains(&tag_article_model) {
            self.articles_tag_added.remove(&tag_article_model);
        } else {
            self.articles_tag_removed.insert(tag_article_model);
        }
    }

    pub fn add_feed_mark_read(&mut self, id: &FeedID) {
        self.feeds_marked_read.insert(id.clone());
    }

    pub fn add_category_mark_read(&mut self, id: &CategoryID) {
        self.categories_marked_read.insert(id.clone());
    }

    pub fn add_tag_mark_read(&mut self, id: &TagID) {
        self.tags_marked_read.insert(id.clone());
    }

    pub fn process_sync_result(&self, sync_result: SyncResult) -> SyncResult {
        let SyncResult {
            feeds,
            categories,
            feed_mappings,
            category_mappings,
            tags,
            headlines,
            articles,
            enclosures,
            taggings,
        } = sync_result;

        let articles = if !self.articles_marked_read.is_empty()
            || !self.articles_marked_unread.is_empty()
            || !self.articles_marked.is_empty()
            || !self.articles_unmarked.is_empty()
            || !self.feeds_marked_read.is_empty()
        {
            articles.map(|vec| {
                vec.into_iter()
                    .map(|mut a| {
                        if self.articles_marked_read.contains(&a.article_id) {
                            a.unread = Read::Read
                        }
                        if self.articles_marked_unread.contains(&a.article_id) {
                            a.unread = Read::Unread
                        }
                        if self.articles_marked.contains(&a.article_id) {
                            a.marked = Marked::Marked
                        }
                        if self.articles_unmarked.contains(&a.article_id) {
                            a.marked = Marked::Unmarked
                        }
                        if self.feeds_marked_read.contains(&a.feed_id) {
                            a.unread = Read::Read
                        }
                        a
                    })
                    .collect::<Vec<FatArticle>>()
            })
        } else {
            articles
        };

        // mark tags read
        let articles = if !self.tags_marked_read.is_empty() {
            self.process_tag_marked_read(articles, &taggings, &self.tags_marked_read)
        } else {
            articles
        };

        // mark categories read
        let articles = if !self.categories_marked_read.is_empty() {
            let read_categories_feeds = Self::build_category_feed_ids(&self.categories_marked_read, &feed_mappings);

            if let Some(read_categories_feeds) = read_categories_feeds {
                self.process_feed_marked_read(articles, &read_categories_feeds)
            } else {
                articles
            }
        } else {
            articles
        };

        // tag/untag articles
        let taggings = if !self.articles_tag_added.is_empty() || !self.articles_tag_removed.is_empty() {
            self.process_tag_articles(taggings, &self.articles_tag_added, &self.articles_tag_removed)
        } else {
            taggings
        };

        SyncResult {
            feeds,
            categories,
            feed_mappings,
            category_mappings,
            tags,
            headlines,
            articles,
            enclosures,
            taggings,
        }
    }

    fn process_feed_marked_read(&self, articles: Option<Vec<FatArticle>>, feed_ids: &HashSet<FeedID>) -> Option<Vec<FatArticle>> {
        articles.map(|vec| {
            vec.into_iter()
                .map(|mut a| {
                    if feed_ids.contains(&a.feed_id) {
                        a.unread = Read::Read
                    }
                    a
                })
                .collect::<Vec<FatArticle>>()
        })
    }

    fn process_tag_marked_read(
        &self,
        articles: Option<Vec<FatArticle>>,
        taggings: &Option<Vec<Tagging>>,
        tag_ids: &HashSet<TagID>,
    ) -> Option<Vec<FatArticle>> {
        let mut tagged_articles: HashSet<ArticleID> = HashSet::new();
        if let Some(vec) = taggings {
            for tagging in vec {
                if tag_ids.contains(&tagging.tag_id) {
                    tagged_articles.insert(tagging.article_id.clone());
                }
            }
        }
        articles.map(|vec| {
            vec.into_iter()
                .map(|mut a| {
                    if tagged_articles.contains(&a.article_id) {
                        a.unread = Read::Read
                    }
                    a
                })
                .collect::<Vec<FatArticle>>()
        })
    }

    fn process_tag_articles(
        &self,
        taggings: Option<Vec<Tagging>>,
        tag_articles: &HashSet<Tagging>,
        untag_articles: &HashSet<Tagging>,
    ) -> Option<Vec<Tagging>> {
        let taggings = taggings.map(|mut vec| {
            vec.append(&mut tag_articles.iter().cloned().collect::<Vec<Tagging>>());
            vec
        });
        taggings.map(|mut vec| {
            for t in untag_articles {
                if let Some(index) = vec.iter().position(|a| a == t) {
                    vec.remove(index);
                }
            }
            vec
        })
    }

    fn build_category_feed_ids(category_ids: &HashSet<CategoryID>, mappings: &Option<Vec<FeedMapping>>) -> Option<HashSet<FeedID>> {
        mappings.as_ref().map(|vec| {
            vec.iter()
                .filter_map(|m| {
                    if category_ids.contains(&m.category_id) {
                        Some(m.feed_id.clone())
                    } else {
                        None
                    }
                })
                .collect::<HashSet<FeedID>>()
        })
    }

    pub async fn execute_api_actions(&self, api: &RwLock<Box<dyn FeedApi>>, client: &Client) -> Result<(), FeedApiError> {
        let api_lock = api.read().await;

        if api_lock.is_logged_in(client).await? {
            if !self.articles_marked_read.is_empty() {
                api_lock
                    .set_article_read(&self.articles_marked_read.iter().cloned().collect::<Vec<ArticleID>>(), Read::Read, client)
                    .await?;
            }
            if !self.articles_marked_unread.is_empty() {
                api_lock
                    .set_article_read(
                        &self.articles_marked_unread.iter().cloned().collect::<Vec<ArticleID>>(),
                        Read::Unread,
                        client,
                    )
                    .await?;
            }
            if !self.articles_marked.is_empty() {
                api_lock
                    .set_article_marked(&self.articles_marked.iter().cloned().collect::<Vec<ArticleID>>(), Marked::Marked, client)
                    .await?;
            }
            if !self.articles_unmarked.is_empty() {
                api_lock
                    .set_article_marked(
                        &self.articles_unmarked.iter().cloned().collect::<Vec<ArticleID>>(),
                        Marked::Unmarked,
                        client,
                    )
                    .await?;
            }
            if !self.feeds_marked_read.is_empty() {
                api_lock
                    .set_feed_read(&self.feeds_marked_read.iter().cloned().collect::<Vec<FeedID>>(), &[], client)
                    .await?;
            }
            if !self.categories_marked_read.is_empty() {
                api_lock
                    .set_category_read(&self.categories_marked_read.iter().cloned().collect::<Vec<CategoryID>>(), &[], client)
                    .await?;
            }
            if !self.tags_marked_read.is_empty() {
                api_lock
                    .set_tag_read(&self.tags_marked_read.iter().cloned().collect::<Vec<TagID>>(), &[], client)
                    .await?;
            }
        }
        Ok(())
    }

    pub fn reset(&mut self) {
        self.articles_marked_read.clear();
        self.articles_marked_unread.clear();
        self.articles_marked.clear();
        self.articles_unmarked.clear();
        self.articles_tag_added.clear();
        self.articles_tag_removed.clear();
        self.feeds_marked_read.clear();
        self.categories_marked_read.clear();
        self.tags_marked_read.clear();
    }
}
