package xyz.mkotb.reddigram.live;

import net.dean.jraw.models.Submission;
import xyz.mkotb.reddigram.ReddigramBot;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LiveManager {
    public static final Pattern LINK_PATTERN = Pattern.compile("reddit.com\\/live\\/(.{12})");
    private final ReddigramBot bot;
    private final Map<String, LiveFollower> followingThreads = new ConcurrentHashMap<>();

    public LiveManager(ReddigramBot bot) {
        this.bot = bot;

        // TODO load saved threads
    }

    public void subscribeTo(String thread, String chat) {
        if (!followingThreads.containsKey(thread)) {
            LiveFollower follower = new LiveFollower(bot, thread, chat);

            follower.start();
            followingThreads.put(thread, follower);
            return;
        }

        followingThreads.get(thread).subscribe(chat);
    }

    public void unsubscribe(String thread, String chat) {
        if (followingThreads.containsKey(thread)) {
            followingThreads.get(thread).unsubscribe(chat);
        }
    }

    public boolean isFollowingThreads(String chat) {
        return followingThreads.values().stream().anyMatch((follower) -> follower.isSubscribed(chat));
    }

    void removeThread(String thread) {
        followingThreads.remove(thread);
    }

    public String idFromSubmission(Submission submission) {
        String link;

        if (submission.getUrl() != null && !submission.getUrl().isEmpty()) {
            link = submission.getUrl();
        } else if (submission.getSelftext() != null && !submission.getSelftext().isEmpty()) {
            link = submission.getSelftext();
        } else {
            return null;
        }

        Matcher matcher = LINK_PATTERN.matcher(link);

        matcher.find();
        return matcher.group(1);
    }
}

@@ -1478,16 +1478,21 @@
 ing link
+ = %22%22
 ;%0A%0A     
@@ -1612,21 +1612,115 @@
        %7D
- else
+%0A%0A        Matcher matcher = LINK_PATTERN.matcher(link);%0A%0A        if (!matcher.find()) %7B%0A           
  if (sub
@@ -1795,32 +1795,36 @@
 ) %7B%0A            
+    
 link = submissio
@@ -1852,68 +1852,15 @@
     
-%7D else %7B%0A            return null;%0A        %7D%0A%0A        Matcher
+       
  mat
@@ -1886,33 +1886,40 @@
 .matcher(link);%0A
-%0A
+        
         matcher.
@@ -1922,24 +1922,99 @@
 her.find();%0A
+            %7D else %7B%0A                return null;%0A            %7D%0A        %7D%0A%0A
         retu

fix bug with /live