"""/r/commentmod alerts"""
# pylint: disable=C0103,C0111
import logging

from .slack_webhook import SlackWebhook as sb
from .database import is_read, mark_read
from .util import get_age, get_submission_link

TABLE = 'commentmod_read'
MAX_AGE = 60 * 60 * 5
CHANNEL = 'commentmods'

logger = logging.getLogger(__name__)


def submission_handler(reddit, db):
    """Retrieve inbox and route messages to individual alerts"""
    cmod = reddit.subreddit('worldnewscommentmods')
    for submission in cmod.new(limit=5):
        if is_read(db, TABLE, submission.name):
            continue

        # dispatchers
        new_post(submission)

        mark_read(db, TABLE, submission.name)


def new_post(submission):
    age = get_age(submission.created_utc)
    if age > MAX_AGE:
        return

    link = get_submission_link(submission.name)

    logger.info('New /r/worldnewscommentmods post: %s', link)
    sb.send('New /r/worldnewscommentmods submission by {author}:'
            ' [<{url}|{title}>]'.format(author=submission.author.name, 
				        url=link,
			 		title=submission.title),
            CHANNEL)
