package eu.toldi.rss;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamOmitField;

import javax.swing.tree.DefaultMutableTreeNode;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@XStreamAlias("feedGroup")
public class FeedGroup extends Feed {

    List<Feed> feedList = new ArrayList<Feed>();
    @XStreamOmitField
    List<Article> articleList = new ArrayList<Article>();

    public FeedGroup(String name){
        super(name);
    }

    public void addFeed(Feed feed){
        if(!feedExists(feed)) {
            feedList.add(feed);
            for (int i = 0; i < feed.getArticleCount(); i++) {
                articleList.add(feed.get(i));
            }
        }else
            System.out.println("Feed exists");
    }

    public boolean feedExists(Feed f){
        for (int i = 0; i < feedList.size(); i++) {
            if(f == feedList.get(i))
                return true;
        }
        return false;
    }

    @Override
    public Article get(int i) {
        return articleList.get(i);
    }

    @Override
    public void updateFeed() throws IOException {
        for (Feed f:feedList) {
            f.updateFeed();
        }
    }

    @Override
    public int getArticleCount() {
        int result = 0;
        for (Feed f:feedList) {
            result += f.getArticleCount();
        }
        return result;
    }

    @Override
    public DefaultMutableTreeNode getTreeNode() {
        DefaultMutableTreeNode folder = super.getTreeNode();
        for (Feed f: feedList) {
            folder.add(f.getTreeNode());
        }
        return folder;
    }

    public void removeFeed(Feed feed){
        boolean found = false;
        for (int i = 0; i < feedList.size(); i++) {
            //Csak ha PONTOSAN megegyezik
            if(feedList.get(i) == feed){
                feedList.remove(i);
                found =true;
                break;
            }
        }
        if(found){
            List<Article> similar = new ArrayList<Article>( articleList );
            List<Article> different = new ArrayList<Article>();
            different.addAll( articleList );
            different.addAll( feed.getArticleList() );

            similar.retainAll( feed.getArticleList() );
            different.removeAll( similar );
            articleList = different;
        }
    }
    public void setLocation(Feed f,int index){
        feedList.remove(f);
        feedList.add(index,f);
    }

}
