import discord_logging
import traceback
from datetime import datetime

log = discord_logging.get_logger()

import counters
import utils
import static
from classes.subscription import Subscription
from classes.comment import DbComment
from praw_wrapper import ReturnType, id_from_fullname, PushshiftType


def process_comment(comment, reddit, database, count_string=""):
	if comment['author'] == static.ACCOUNT_NAME:
		log.info(f"{count_string}: Comment is from updatemebot")
		return
	if comment['author'] in static.BLACKLISTED_ACCOUNTS:
		log.info(f"{count_string}: Comment is from a blacklisted account")
		return

	counters.replies.labels(source='comment').inc()

	log.info(f"{count_string}: Processing comment {comment['id']} from u/{comment['author']}")
	body = comment['body'].lower().strip()
	use_tag = True
	if static.TRIGGER_SUBSCRIBE_LOWER in body:
		log.debug("Subscription comment")
		recurring = True
	elif static.TRIGGER_UPDATE_LOWER in body:
		log.debug("Update comment")
		recurring = False
	elif static.TRIGGER_SUBSCRIBE_ALL_LOWER in body:
		log.debug("Subscribe all comment")
		recurring = True
		use_tag = False
	else:
		log.debug("Command not in comment")
		return

	comment_result = None
	thread_id = id_from_fullname(comment['link_id'])
	subscriber = database.get_or_add_user(comment['author'])
	subreddit = database.get_or_add_subreddit(comment['subreddit'])
	db_submission = database.get_submission_by_id(thread_id)
	tag = None
	if db_submission is not None:
		author = db_submission.author
		if use_tag:
			tag = db_submission.tag
	else:
		comment_result = ReturnType.SUBMISSION_NOT_PROCESSED
		reddit_submission = reddit.get_submission(thread_id)
		try:
			author_name = reddit_submission.author.name
		except Exception:
			log.warning(f"Unable to fetch parent submission for comment: {thread_id}")
			return
		author = database.get_or_add_user(author_name)

	result_message, subscription = Subscription.create_update_subscription(
		database, subscriber, author, subreddit, recurring, tag
	)

	commented = False
	if db_submission is not None and db_submission.comment is not None:
		comment_result = ReturnType.THREAD_REPLIED
	elif subreddit.is_banned or subreddit.no_comment:
		comment_result = ReturnType.FORBIDDEN
	elif not subreddit.is_enabled:
		comment_result = ReturnType.SUBREDDIT_NOT_ENABLED
	if comment_result is None:
		reddit_comment = reddit.get_comment(comment['id'])
		count_subscriptions = database.get_count_subscriptions_for_author_subreddit(author, subreddit, tag)
		db_comment = DbComment(
			comment_id=None,
			submission=db_submission,
			subscriber=subscriber,
			author=author,
			subreddit=subreddit,
			recurring=recurring,
			current_count=count_subscriptions,
			tag=tag