from flask_login import current_user
from app import app, db
from app.forms.login import LoginForm
from app.forms.search import SearchForm
from app.models.forum import Forum
from app.models.topic import Topic



@app.context_processor
def menu_processor():
    """ All items used to render main menu. Includes search form """

    login_form = LoginForm(prefix="menu_")
    search_form = SearchForm()
    main_forum = Forum.query.filter_by(parent=None).first()

    # Constructing last active topics
    rows = db.session.execute( """SELECT topic.id FROM topic
        INNER JOIN comment ON topic.thread_id = comment.thread_id
        INNER JOIN post ON post.id = comment.id
        GROUP BY topic.id
        ORDER BY MAX(post.date_created) DESC
        LIMIT 20;""")
    ids = [row[0] for row in rows]
    # Somewhat inelegant, but much better than loading individually
    recent_topics = db.session.query(Topic).filter(Topic.id.in_(ids)).all()
    recent_topics = sorted(recent_topics, key=lambda t: ids.index(t.id))


    # Filter the topics the user can view and limit to 10
    if current_user.is_authenticated:
        f = lambda t: current_user.can_access_forum(t.forum)
    else:
        f = lambda t: t.forum.is_default_accessible()

    recent_topics = list(filter(f, recent_topics))[:10]

    # Constructing last news
    rows = db.session.execute( """SELECT topic.id FROM topic
        INNER JOIN forum ON topic.forum_id = forum.id
        INNER JOIN comment ON topic.thread_id = comment.thread_id
        INNER JOIN post ON post.id = comment.id
        WHERE forum.url LIKE '/actus%'
        GROUP BY topic.id
        ORDER BY MIN(post.date_created) DESC
        LIMIT 10;
        """)
    ids = [row[0] for row in rows]
    recent_news = db.session.query(Topic).filter(Topic.id.in_(ids)).all()
    recent_news = sorted(recent_news, key=lambda t: ids.index(t.id))

    return dict(login_form=login_form, search_form=search_form,
        main_forum=main_forum, last_active_topics=recent_topics,
        last_news=recent_news)
