# resolution stuff

import sys
import time
import requests # To suppress requests error messages
from colors import paint
from re import findall, DOTALL
from lib.identity import identification
from core.info import notifications, Help
from lib.functions import utilities

class NeglectedErrors(RuntimeError):
    pass

class resolve(identification):
    """
    Elements that can be used to resolve from a photo, etc.
    """

    def __init__(self):
        self.notifications = notifications()
        self.utilities = utilities()

        self.found_tags_l = []
        self.found_tags_u = {}

    # Main function, which triggers everything else.
    def CDNPhoto(self, CDNL):
        # Initial Function Variable containers
        if "https://www.facebook.com/photo.php?fbid=" in CDNL:
            PICID = CDNL.replace('https://www.facebook.com/photo.php?fbid=', '')

        elif 'a.akamaihd.net' or 'fbcdn.net/hphotos' or 'fbcdn.net' in CDNL:
            PICURL1 = CDNL[:] # Invite CDN url in as a list
            PICID =  PICURL1.split('_')[1] # Identifies who the pictures belongs to.

        elif 'a.akamaihd.net' or 'https://www.facebook.com/photo.php?fbid=' not in CDNL:
            self.utilities.pi("\n" + self.notifications.INFO + "Couldn't parse non-CDN Photo link!\n")
            exit(1)

        APIURL = "https://graph.facebook.com/" # Facebooks free api to abuse.
        IPU  = "https://www.facebook.com/photo.php?fbid=" # Initial Photo URL | for photo resolution
        PLU = "https://www.facebook.com/" # Profile Link URL

        # Initial Variables for actionable responses
        APILINK = APIURL + PICID # API Response from picture ID, if it directly connects back to a profile.
        ALBUMURL = IPU + PICID # The link back to the photo you are resolving.
        DPL = PLU + PICID # Direct Profile Link
        APIRESPONSE = self.utilities.GetHTTPRequest(APILINK).json()
        PHOTOPAGERESPONSE = self.utilities.GetHTTPRequest(ALBUMURL).content
        GROUPIDRESPONSE = self.GroupID(PHOTOPAGERESPONSE)
        COMMENTSRESPONSE = self.PeopleFromComments(PHOTOPAGERESPONSE)
        HASHTAGRESPONSE = self.HashTag(PHOTOPAGERESPONSE)
        PHOTOTIMESTAMP = self.PhotoTimeStamp(PHOTOPAGERESPONSE)
        COMMENTTIMESTAMP = self.CommentTimeStamps(PHOTOPAGERESPONSE)
        COMMENTCOUNT = self.CommentCount(PHOTOPAGERESPONSE)

        # Initial Variables for specific extraction
        PFNC = findall(r'<title id="pageTitle">.*?</title>', PHOTOPAGERESPONSE, DOTALL) # Extract type
        IPNC = PFNC[0].replace('<title id="pageTitle">', "").replace('</title>', "").replace('| Facebook', "") # Extract type name from tag
        PNC1 = IPNC + "'s" # For display code only | don't remove.

        # Mandatory check to see if a photos information can be accessed.
        # If this conditional is not place above the Instantiated functions below, then you will break the application completely.

        if IPNC == "Facebook":
            self.utilities.pi("\n" + self.notifications.INFO + "Couldn't find photo information due to privacy settings.\n")
            exit(0)

        print ""

        # Instantiated functions, that if otherwise break this app if moved.
        PROFILELINK = PLU + self.ProfileLink(PHOTOPAGERESPONSE)
        PROFILENAME = self.ProfileName(PHOTOPAGERESPONSE)
        ALBUMTYPE = self.PhotoAlbum(PHOTOPAGERESPONSE).replace('&#039;', "'")

        # User information for photo report.
        PEOPLE4PHOTOREPORT = []
        PHOTOREPORTUSERNAME = PROFILENAME
        PHOTOREPORTID = PROFILELINK.replace("https://www.facebook.com/", '')

        if APIRESPONSE.has_key('from') is True and APIRESPONSE['from'].has_key('id') is True and APIRESPONSE['from'].has_key('name') is True and PROFILENAME != "Facebook":
            self.utilities.pi(self.notifications.INFO + "Resolving {} Photo ...".format(APIRESPONSE['from']['name'] + "'s"))
            self.utilities.pi(self.notifications.POSTEDON + PHOTOTIMESTAMP)

            if PROFILELINK == []:
                self.utilities.pi(self.notifications.OWNER + APIRESPONSE['from']['name'] + " - " + PROFILELINK)
                self.utilities.pi(ALBUMTYPE)

            elif PROFILELINK != []:
                self.utilities.pi(self.notifications.OWNER + str(APIRESPONSE['from']['name']) + " - " + PROFILELINK)
                self.utilities.pi(ALBUMTYPE)

        if APIRESPONSE.has_key('from') is False and "Facebook" not in IPNC:
            self.utilities.pi(self.notifications.INFO + "Resolving {} Photo ...".format(PROFILENAME + "'s"))
            self.utilities.pi(self.notifications.POSTEDON + PHOTOTIMESTAMP)

            if PROFILELINK == []:
                self.utilities.pi(self.notifications.OWNER + PROFILENAME + " - " + PROFILELINK)
                self.utilities.pi(ALBUMTYPE)

            elif PROFILELINK != []:
                self.utilities.pi(self.notifications.OWNER + PROFILENAME + " - " + PROFILELINK)
                self.utilities.pi(ALBUMTYPE)

        # If hashtags exist in photo, respond accordingly.
        if HASHTAGRESPONSE is not False and HASHTAGRESPONSE is not None and HASHTAGRESPONSE != []:
            if len(HASHTAGRESPONSE) is 1:
                self.utilities.pi("\n" + self.notifications.INFO + PROFILENAME + " " + "mentioned this topic in the Photo:")

            if len(HASHTAGRESPONSE) > 1:
                self.utilities.pi("\n" + self.notifications.INFO + PROFILENAME + " " + "mentioned these topics in the Photo:")

            for instance in HASHTAGRESPONSE:
                link = instance.replace('" data-ft="&#', '')
                tag  = link.replace('https://www.facebook.com/hashtag/', '')
                self.utilities.pi(self.notifications.HASHTAG + "#" + tag + " - " + link)

        # Respond when a group id is found.
        if GROUPIDRESPONSE is not False:
            GIDJR  = self.utilities.GetHTTPRequest(APIURL + GROUPIDRESPONSE).json()
            self.utilities.pi(self.notifications.INFO + "This Photo was posted to a group: {}.".format(paint.B+GIDJR['name']+paint.N))

            self.utilities.pi(self.notifications.INFO + "Here's more info on the owner of {}.".format(paint.B+GIDJR['name']+paint.N))

            self.utilities.pi(self.notifications.GROUPOWNERP + GIDJR['owner']['name'])

            self.utilities.pi(self.notifications.GROUPOWNERID + GIDJR['owner']['id'])

            GIDJSR2 = self.utilities.GetHTTPRequest(APIURL + GIDJR['owner']['id']).json()
            self.utilities.pi(self.notifications.GROUPOWNERPROFILE + PLU + GIDJSR2['username'])

        # Grab some people who commented on a photo.
        # Response when a 1 or more comments are found.
        if COMMENTSRESPONSE is not False:

            if len(COMMENTSRESPONSE) > 1:
                self.utilities.pi("\n{} These people commented on {} photo:".format(self.notifications.INFO,PROFILENAME + "'s"))

            if len(COMMENTSRESPONSE) is 1:
                self.utilities.pi("\n{}This person commented on {} photo:".format(self.notifications.INFO, PROFILENAME + "'s"))


            for CommentID, CommentTime in zip(COMMENTSRESPONSE, COMMENTTIMESTAMP):
                CommentID = CommentID.replace('"author":"', '').replace('"', '').replace(',', '')

                if CommentID is not "":
                    CIDJR = self.utilities.GetHTTPRequest(APIURL + CommentID).json()
                    #print CIDJR

                # Verify that it's a page.
                if CIDJR.has_key('about') is True and CIDJR.has_key('can_post') is True and CIDJR.has_key('category') is True:
                    print self.notifications.COMMENT + CIDJR['name'] + ' - ' + CIDJR['link']

                # Verify that it's a user.
                if CIDJR.has_key('first_name') is True and CIDJR.has_key('last_name') is True and CIDJR.has_key('id') is True:
                    print self.notifications.COMMENT + CommentTime + " - " + PLU + CIDJR['id']
                    #PEOPLE4PHOTOREPORT.append('[COMMENTED]: ' + CommentTime + " - " + CIDJR['first_name'] +', ' + CIDJR['last_name'] + ' - ' + PLU + CIDJR['username'])

                # If User doesn't exist, pass.
                if CIDJR.has_key('error') is True:
                    pass

        # Get all tagged people in photo
        CaughtInPhoto = self.TaggedPeople(PHOTOPAGERESPONSE) # If anyone is tagged in the photo, get them.
        if CaughtInPhoto != []:

            cc = []
            for duplicate in CaughtInPhoto:
                cc.append(duplicate)

            UOD = {}
            for item in cc:
                UOD[item] = 1
            count = UOD.keys()

            if len(count) is 1:
                self.utilities.pi("\n{}This person was tagged in {} Photo:".format(self.notifications.INFO, PROFILENAME + "'s"))

            if len(count) > 1:
                self.utilities.pi("\n{}These people were tagged in {} Photo:".format(self.notifications.INFO, PROFILENAME + "'s"))

            # This operation makes sure one of each person tagged in photo gets printed
            for person in CaughtInPhoto:
                person = person.replace('perm:tag:', '').replace('"', "")
                self.found_tags.append(person)

            for item in self.found_tags:
                self.found_tags_u[item] = 1
            keys = self.found_tags_u.keys()

            for person in keys:
                rr = self.utilities.GetHTTPRequest(APIURL + person)

                if rr.status_code == 200:
                    rr = rr.json()
                    #Conditionals cases for the correct output of tagged users
                    if rr.has_key('username') is True:
                        self.utilities.pi(self.notifications.TAGGED + rr['first_name'] + ", " + rr['last_name'] + " - " + PLU + rr["username"])
                        PEOPLE4PHOTOREPORT.append('[TAGGED]: ' + PLU + rr["username"].encode('utf-8'))

                    if rr.has_key('username') is False:
                        self.utilities.pi(self.notifications.TAGGED + rr['first_name'] + ", " + rr['last_name']  + " - " + paint.R + "No link traceback." + paint.N)
                        PEOPLE4PHOTOREPORT.append(rr['first_name'].encode('utf-8') + ", " + rr['last_name'].encode('utf-8'))

                else:
                    pass

        if PEOPLE4PHOTOREPORT != []:
            # May run statistics in later versions.
            pass
        self.utilities.pi("") # Making the output look better.
