import nltk
import datetime


def intersect(titles):

    ret_set = set(titles[0])

    for index, element in enumerate(titles):
        if index > 0:
            ret_set = ret_set & set(element)

    return list(ret_set)


class Filters:

    """This module implements a set of filters through which submissions can be ran through"""

    current_events = []

    def __init__(self, r, s):

        self.r = r
        self.s = s
        self.already_done = []
        self.already_checked_cur_events = []
        self.tags = ('NN', 'NNP', 'NNPS', 'JJ', 'NNS', 'VBG', 'VB', 'VBN', 'CD', 'RB', 'VBD')

    def _create_c_events_rule(self, search_results):

        list_of_tokenized_titles = []
        final_words_list = []

        for index, submission in enumerate(search_results):

            if index <= 3:

                tokenized_title = submission.title.lower().split()

                list_of_tokenized_titles.append(tokenized_title)

            submission.remove()

        title_words_list = intersect(list_of_tokenized_titles)

        tokens = nltk.word_tokenize(' '.join(title_words_list))
        tagged = nltk.pos_tag(tokens)

        for word, tag in tagged:

            if tag in self.tags:
                final_words_list.append(word)

        final_words_list.remove('eli5')

        self.current_events.append(final_words_list)

        self.s.send_msg("Created cur event rule: %s" % ' '.join(final_words_list), channel_name="eli5bot-dev",
                        confirm=False)

    def _get_broken_cur_event(self, title_words_list):

        print("1")
        broken_event = None
        print(str(self.current_events))

        for title in self.current_events:

            broken_event = title

            print("Checking " + str(title_words_list))
            got_intersection = set(title) & set(title_words_list)
            print(str(got_intersection))

            if got_intersection:
                break

        if broken_event is not None:
            ret = ' '.join(broken_event)
        else:
            ret = None

        print("ret " + str(ret))

        return ret

    def check_current_events(self, submissions):

        for submission in submissions:

            if submission.id not in self.already_checked_cur_events:
                title_words_list = nltk.word_tokenize(submission.title.lower())

                print(submission.id)
                print(str(title_words_list))

                broken_event = self._get_broken_cur_event(title_words_list)

                if broken_event is not None:
                    submission.report("Current event: %s" % broken_event)

                self.already_checked_cur_events.append(submission.id)

    def search_reposts(self, submissions):

        nltk.data.path.append('./nltk_data/')

        for submission in submissions:

            if submission.id not in self.already_done:

                words_list = []
                search_results_in_last_threehours = []
                total_in_threehours = 0
                title = submission.title.lower()
                self.already_done.append(submission.id)

                tokens = nltk.word_tokenize(title)
                tagged = nltk.pos_tag(tokens[1:])

                print(str(tagged))

                for word, tag in tagged:

                    if tag in self.tags:
                        words_list.append(word)

                search_query = ' '.join(words_list)
                full_search_query = "title:(" + search_query + ")"

                print(str(full_search_query))

                search_result = self.r.search(full_search_query, subreddit="santi871", sort='new')
                search_result_list = list(search_result)

                for item in search_result_list:

                    comment_time = datetime.datetime.fromtimestamp(item.created_utc)
                    d = datetime.datetime.now() - comment_time
                    delta_time = d.total_seconds()

                    if int(delta_time / 60) < 180:
                        total_in_threehours += 1
                        search_results_in_last_threehours.append(item)

                print(str(search_results_in_last_threehours))

                if len(search_result_list) >= 4:

                    msg_string = "---\n*Potential repost detected*\n" + \
                                 title + '\n' + "*POS tagger output:* " + str(tagged) + '\n' + \
                                 '*Link:* ' + submission.permalink + '\n' + "*Search query:* " + full_search_query + \
                                 '\n' + '*Search results:*\n'

                    for item in search_result_list:
                        msg_string += str(item) + '\n'

                    msg = self.s.send_msg(msg_string, channel_name="eli5bot-dev", confirm=False)

                    submission.report("Potential repost")

                if total_in_threehours >= 3:
                    msg_string = "---\n*Potential large influx of question*\n" + \
                                 title + '\n' + "*Search query:* " + full_search_query + '\n' + '*Link:* ' + \
                                 submission.permalink

                    msg = self.s.send_msg(msg_string, channel_name="eli5bot-dev", confirm=False)

                    self._create_c_events_rule(search_results_in_last_threehours)

@@ -1291,24 +1291,222 @@
 ve('eli5')%0A%0A
+        try:%0A            final_words_list.remove(':')%0A        except ValueError:%0A            pass%0A%0A        try:%0A            final_words_list.remove(';')%0A        except ValueError:%0A            pass%0A%0A
         self
@@ -1758,27 +1758,8 @@
 ):%0A%0A
-        print(%221%22)%0A
     
@@ -1786,49 +1786,8 @@
 one%0A
-        print(str(self.current_events))%0A%0A
     
@@ -1863,63 +1863,8 @@
 le%0A%0A
-            print(%22Checking %22 + str(title_words_list))%0A
     
@@ -1928,49 +1928,8 @@
 ist)
-%0A            print(str(got_intersection))
 %0A%0A  
@@ -2102,42 +2102,8 @@
 ne%0A%0A
-        print(%22ret %22 + str(ret))%0A%0A
     
@@ -2362,91 +2362,8 @@
 ))%0A%0A
-                print(submission.id)%0A                print(str(title_words_list))%0A%0A
     
@@ -3118,75 +3118,316 @@
    t
-agged = nltk.pos_tag(tokens%5B1:%5D)%0A%0A                print(str(tagged)
+okens.remove('eli5')%0A%0A                try:%0A                    tokens.remove(':')%0A                except ValueError:%0A                    pass%0A%0A                try:%0A                    tokens.remove(';')%0A                except ValueError:%0A                    pass%0A%0A                tagged = nltk.pos_tag(tokens
 )%0A%0A 
@@ -3681,55 +3681,8 @@
 )%22%0A%0A
-                print(str(full_search_query))%0A%0A
     
@@ -4259,71 +4259,8 @@
 m)%0A%0A
-                print(str(search_results_in_last_threehours))%0A%0A
     

remove : and ;