__author__ = 'DarkWeb'

# Here, we are importing the auxiliary functions to clean or convert data
from Forums.Utilities.utilities import *
from datetime import date
from datetime import timedelta
import re

# Here, we are importing BeautifulSoup to search through the HTML tree
from bs4 import BeautifulSoup

# This is the method to parse the Description Pages (one page to each topic in the Listing Pages)


def cryptBB_description_parser(soup):

    # Fields to be parsed

    topic = "-1"            # 0 *topic name
    user = []               # 1 *all users of each post
    status = []             # 2 all user's authority in each post such as (adm, member, dangerous)
    reputation = []         # 3 all user's karma in each post (usually found as a number)
    interest = []           # 4 all user's interest in each post
    sign = []               # 5 all user's signature in each post (usually a standard message after the content of the post)
    post = []               # 6 all messages of each post
    feedback = []           # 7 all feedbacks of each vendor (this was found in just one Forum and with a number format)
    addDate = []            # 8 all dates of each post
    image_user = []         # 9 all user avatars of each post
    image_post = []         # 10 all first images of each post

    # Finding the topic (should be just one coming from the Listing Page)

    li = soup.find("td", {"class": "thead"}).find('strong')
    topic = li.text
    topic = re.sub("\[\w*\]", '', topic)

    topic = topic.replace(",","")
    topic = topic.replace("\n","")
    topic = cleanString(topic.strip())

    # Finding the repeated tag that corresponds to the listing of posts

    posts = soup.find('table', {"class": "tborder tfixed clear"}).find('td', {"id": "posts_container"}).find_all(
        'div', {"class": "post"})

    # For each message (post), get all the fields we are interested to:

    for ipost in posts:

        if ipost.find('div', {"class": "deleted_post_author"}):
            continue

        # Finding a first level of the HTML page

        post_wrapper = ipost.find('span', {"class": "largetext"})

        # Finding the author (user) of the post

        author = post_wrapper.text.strip()
        user.append(cleanString(author))  # Remember to clean the problematic characters

        # Finding the status of the author

        smalltext = ipost.find('div', {"class": "post_author"})

        if smalltext is not None:

            # CryptBB does have membergroup and postgroup
            membergroup = smalltext.find('div', {"class": "profile-rank"})
            postgroup = smalltext.find('div', {"class": "postgroup"})
            if membergroup != None:
                membergroup = membergroup.text.strip()
                if postgroup != None:
                    postgroup = postgroup.text.strip()
                    membergroup = membergroup + " - " + postgroup
            else:
                if postgroup != None:
                    membergroup = postgroup.text.strip()
                else:
                    membergroup = "-1"
            status.append(cleanString(membergroup))

            # Finding the interest of the author
            # CryptBB does not have blurb
            blurb = smalltext.find('li', {"class": "blurb"})
            if blurb != None:
                blurb = blurb.text.strip()
            else:
                blurb = "-1"
            interest.append(cleanString(blurb))

            # Finding the reputation of the user
            # CryptBB does have reputation
            author_stats = smalltext.find('div', {"class": "author_statistics"})
            karma = author_stats.find('strong')
            if karma != None:
                karma = karma.text
                karma = karma.replace("Community Rating: ", "")
                karma = karma.replace("Karma: ", "")
                karma = karma.strip()
            else:
                karma = "-1"
            reputation.append(cleanString(karma))

        else:
            status.append('-1')
            interest.append('-1')
            reputation.append('-1')

        # Getting here another good tag to find the post date, post content and users' signature

        postarea = ipost.find('div', {"class": "post_content"})

        dt = postarea.find('span', {"class": "post_date"}).text
        # dt = dt.strip().split()
        dt = dt.strip()
        day=date.today()
        if "Today" in dt:
            today = day.strftime('%m-%d-%Y')
            stime = dt.replace('Today,','').strip()
            date_time_obj = today + ', '+stime
            date_time_obj = datetime.strptime(date_time_obj,'%m-%d-%Y, %I:%M %p')
        elif "Yesterday" in dt:
            yesterday = day - timedelta(days=1)
            yesterday = yesterday.strftime('%m-%d-%Y')
            stime = dt.replace('Yesterday,','').strip()
            date_time_obj = yesterday + ', '+stime
            date_time_obj = datetime.strptime(date_time_obj,'%m-%d-%Y, %I:%M %p')
        elif "ago" in dt:
            date_time_obj = postarea.find('span', {"class": "post_date"}).find('span')['title']
            date_time_obj = datetime.strptime(date_time_obj, '%m-%d-%Y, %I:%M %p')
        else:
            date_time_obj = datetime.strptime(dt, '%m-%d-%Y, %I:%M %p')
        addDate.append(date_time_obj)

        # Finding the post

        inner = postarea.find('div', {"class": "post_body scaleimages"})
        quote = inner.find('blockquote')
        if quote is not None:
            quote.decompose()
        inner = inner.text.strip()
        post.append(cleanString(inner))

        # Finding the user's signature

        # signature = ipost.find('div', {"class": "post_wrapper"}).find('div', {"class": "moderatorbar"}).find('div', {"class": "signature"})
        signature = ipost.find('div', {"class": "signature scaleimages"})
        if signature != None:
            signature = signature.text.strip()
            # print(signature)
        else:
            signature = "-1"
        sign.append(cleanString(signature))

        # As no information about user's feedback was found, just assign "-1" to the variable

        feedback.append("-1")

        img = ipost.find('div', {"class": "post_body scaleimages"}).find('img')
        if img is not None:
            img = img.get('src').split('base64,')[-1]
        else:
            img = "-1"
        image_post.append(img)

        avatar = ipost.find('div', {"class": "author_avatar"})
        if avatar is not None:
           img = avatar.find('img')
           if img is not None:
              img = img.get('src').split('base64,')[-1]
           else:
               img = "-1"
        else:
            img = "-1"
        image_user.append(img)

    # Populate the final variable (this should be a list with all fields scraped)

    row = (topic, user, status, reputation, interest, sign, post, feedback, addDate, image_user, image_post)

    # Sending the results

    return row

# This is the method to parse the Listing Pages (one page with many posts)

def cryptBB_listing_parser(soup):

    nm = 0              # *this variable should receive the number of topics
    forum = "CryptBB"   # 0 *forum name
    board = "-1"        # 1 *board name (the previous level of the topic in the Forum categorization tree.
                        # For instance: Security/Malware/Tools to hack Facebook. The board here should be Malware)
    author = []         # 2 *all authors of each topic
    topic = []          # 3 *all topics
    views = []          # 4 number of views of each topic
    posts = []          # 5 number of posts of each topic
    href = []           # 6 this variable should receive all cleaned urls (we will use this to do the marge between
                        # Listing and Description pages)
    addDate = []        # 7 when the topic was created (difficult to find)
    image_author = []   # 8 all author avatars used in each topic


    # Finding the board (should be just one)

    board = soup.find('span', {"class": "active"}).text
    board = cleanString(board.strip())

    # Finding the repeated tag that corresponds to the listing of topics

    itopics = soup.find_all('tr',{"class": "inline_row"})

    # Counting how many topics

    nm = len(itopics)

    for itopic in itopics:

        # For each topic found, the structure to get the rest of the information can be of two types. Testing all of them
        # to don't miss any topic

        # Adding the topic to the topic list
        try:
            topics = itopic.find('span', {"class": "subject_old"}).find('a').text
        except:
            topics = itopic.find('span', {"class": "subject_new"}).find('a').text
        topics = re.sub("\[\w*\]", '', topics)
        topic.append(cleanString(topics))

        image_author.append(-1)

        # Adding the url to the list of urls
        try:
            link = itopic.find('span', {"class": "subject_old"}).find('a').get('href')
        except:
            link = itopic.find('span',{"class": "subject_new"}).find('a').get('href')
        href.append(link)

        # Finding the author of the topic
        ps = itopic.find('div', {"class":"author smalltext"}).text
        user = ps.strip()
        author.append(cleanString(user))

        # Finding the number of replies
        columns = itopic.findChildren('td',recursive=False)
        replies = columns[3].text
        if replies == '-':
            posts.append('-1')
        else:
            posts.append(cleanString(replies))

        # Finding the number of Views
        tview = columns[4].text
        if tview == '-':
            views.append('-1')
        else:
            views.append(cleanString(tview))

        # If no information about when the topic was added, just assign "-1" to the variable

        addDate.append("-1")

    return organizeTopics(forum, nm, board, author, topic, views, posts, href, addDate, image_author)


def cryptBB_links_parser(soup):

    # Returning all links that should be visited by the Crawler

    href = []

    listing = soup.find('table', {"class": "tborder clear"}).find('tbody').find_all('tr', {"class": "inline_row"})

    for a in listing:
        try:
            link = a.find('span', {"class": "subject_old"}).find('a').get('href')
        except:
            link = a.find('span', {"class": "subject_new"}).find('a').get('href')

        href.append(link)

    return href