import subprocess
import json
from django.conf import settings
from django.utils import timezone

from . import cli
from . import rpc


def main():
    cmd = cli.BASE_CMD + [
        'daemon', '--http', '--send-read-receipts'
    ]
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1, universal_newlines=True, start_new_session=True)
    try:
        for line in p.stdout:
            try:
                msg = json.loads(line)
            except:
                if settings.DEBUG:
                    print(">>", line)
                continue
            if settings.DEBUG:
                print('==', msg)
            source = msg.get('envelope', {}).get('sourceNumber')
            reaction = msg.get('envelope', {}).get('dataMessage', {}).get('reaction', {})
            emoji = reaction.get('emoji')
            target_author = reaction.get('targetAuthorNumber')
            target_ts = reaction.get('targetSentTimestamp')
            group = msg.get('envelope', {}).get('dataMessage', {}).get("groupInfo", {}).get("groupId")
            if group == settings.SIGNAL_MODERATORS_GROUP:
                if emoji == "👍" and target_author == settings.SIGNAL_ACCOUNT:
                    if source in settings.SIGNAL_MODERATORS:
                        from ..item import models, tasks
                        now = timezone.now()
                        try:
                            comment = models.Comment.objects.filter(data__moderator_ts=target_ts).first()
                            if comment:
                                link = settings.URL + comment.item.get_absolute_url()
                                msg = '%s commented on <b>%s</b> at <a href="%s">%s</a>' % (
                                    comment.name, comment.item.title, link, link
                                )
                                tasks.notify_telegram.delay(msg)
                        except:
                            pass
                        models.Comment.objects.filter(data__moderator_ts=target_ts).update(published=now)
                        rpc.send_reaction(target_author, target_ts, "🎉", group=group)
                    else:
                        rpc.send("Ignoring your request, you are not a moderator", group=group)
    except:
        p.kill()