#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- coding: binary -*-

from re import findall, DOTALL
from functions import utilities
from core.info import notifications

class identification(utilities):

    """
    "If you want something, you have to take it. - will smith, Pursuit of happiness."
    """

    def __init__(self):
        self.api = 'https://graph.facebook.com/' # Our main query resource.
        self.main_target = "https://facebook.com/" # Well this is awkward.
        self.notifications = notifications()

    def TaggedPeople(self, content):
        # Grab tagged people in photo.
        self.tagged_person = findall(r'"perm:tag:.*?"', content, DOTALL)
        return self.tagged_person

    def HiddenTaggedPeople(self, content):
        # Hidden tagged users are usually tagged within the photo CAPTION itself.
        return findall(r'<a class="taggee" href="https://www.facebook.com/.*">.*</a>', content)[0]

    def PhotoIdentifier(self, album_link):
        self._photo_identifier_l = []
        self.album_content_container = self.GetHTTPRequest(album_link).text
        self.download = '&dl=1' # Download photo parameter, 1 is used in all of auth procedures.
        photoidregex = findall(r'(https://.*?\?oh=[a-f0-9]{32}\&amp;oe=[a-fA-F0-9]{4,20})', self.album_content_container)

        for CDNPHOTO in photoidregex:
            CDNPHOTO = CDNPHOTO.replace('amp;', '')
            #if 'a.akamaihd.net' or 'fbcdn.net/hphotos' or 'fbcdn.net' in
            if 'https://www.facebook.com/photo.php?fbid=' not in CDNPHOTO:
                if 'https://www.facebook.com/media/' not in CDNPHOTO:
                    if 'sphotos' not in CDNPHOTO:
                        if '_n' in CDNPHOTO:
                            self._photo_identifier_l.append(CDNPHOTO)

        return self._photo_identifier_l

    def AlbumIdentifier(self, photo_album_link):
        # Identifies all the album names
        self.__album_identifiers_l = []
        self.__album_identifiers_u = {}
        content = self.GetHTTPRequest(photo_album_link)

        if content.status_code == 200:
            albumidregex = findall(r'[0-9]{4,18}\.[0-9]{4,18}\.[0-9]{1,18}', content.text)
            albumlink = 'https://www.facebook.com/media/set/?set=a.'

            for ID in albumidregex:
                ID = albumlink + ID
                self.__album_identifiers_l.append(ID)

            for item in self.__album_identifiers_l:
                self.__album_identifiers_u[item] = 1
            return self.__album_identifiers_u.keys()

        else:
            return None

    def AlbumIDN(self, id_number):
        # Takes an IDN (identification number)
        self._album_idn_idl = []
        self._album_idn_idu = {}
        domain = "https://facebook.com/"
        AlbumContentDump = self.GetHTTPRequest('https://www.facebook.com/media/albums/?id={}'.format(id_number)).text
        self.idn_container = findall(r'name="[0-9]{9,17}"', AlbumContentDump)

        for identification_number in self.idn_container:
            identification_number = identification_number.replace('"', '').replace('name=', '')
            self._album_idn_idl.append(self.main_target + ID)

        for item in self._album_idn_idl:
            self._album_idn_idu[item] = 1
        return self._album_idn_idu.keys()

    def AlbumName(self, album_link):
        # Album link is == https://facebook.com/AIDN

        AlbumRegex = self.GetHTTPRequest(album_link).text
        UAN = findall(r'<h1 class="fbPhotoAlbumTitle">(.*)</h1>', AlbumRegex)[-1]
        return UAN

    def PhotoTimeStamp(self, content):
        TimeContainer = findall(r'<abbr.*>.*</abbr>', content)

        if TimeContainer != []:
            TimeC2 = findall(r'title="(.*)"', TimeContainer[0])
            junk = findall(r'" .*', TimeC2[0])
            Time = TimeC2[0].replace(junk[0], '')
            return Time

        if TimeContainer == []:
            return "Date not available." # If that ever happends.

    def CommentTimeStamps(self, content):
        self.tsl = []
        self.comment_timestamps = findall(r'"verbose":".*?"', content)
        for time in self.comment_timestamps:
            time = time.replace('"verbose":"', '').replace('"', '')
            self.tsl.append(time)
        return self.tsl

    def PeopleCommentText(self, content):
        # The text of the people who commented on the photo.
        self.person_comment_text = findall(r'text":".*",', content)
        return self.person_comment_text

    def PeopleFromComments(self, content):
        self._pfc_u = {}
        self._list_of_people_l = []
        self._person = findall(r',"author":".*?"', content)

        if self._person != []:
            for tag in self._person:
                self._list_of_people_l.append(tag)

            for item in self._list_of_people_l:
                self._pfc_u[item] = 1 # Do duplicates.

            return self._pfc_u.keys()
        else:
            return False

    def ProfileLink(self, content):
        POC = findall(r'"owner":.*?,', content)
        ID = POC[0].replace('"owner":', '').replace(',', '')
        return ID

    def GroupID(self, content):
        # If the photo was posted from/to a group then grab the group id(s) and process it.
        gidl = []
        gidu = {}
        try:
            GIDLC = findall(r'/groups/.*?/', content)

            for instance in GIDLC:
                gidl.append(instance)

            for item in gidl:
                gidu[item] = 1
            ID = gidu.keys()[0].replace('/groups/', '').replace('/', '')

            if len(ID) is not 15:
                return False
            else:
                return ID
        except IndexError:
            return False

    def HashTag(self, content):
        self.htl = []
        self.htu = {}
        self.hash_tag = findall(r'https://www.facebook.com/hashtag/.*?#', content)
        for instance in self.hash_tag:
            self.htl.append(instance)

        for item in self.htl:
            self.htu[item] = 1
        keys = self.htu.keys()

        if keys is not []:
            return keys

        else:
            return False

    def CommentCount(self, content):
        self._comment_count_l = findall(r'"commentcount":.*?,', content)

        if self._comment_count_l == []:
            return None

        if self._comment_count_l != []:
            self._comment_count_l_2 = findall(r'"commentcount":.*?,', content)[0].replace('"commentcount":', '').replace(',', '')
            return self._comment_count_l_2

    def ProfileName(self, content):
        # Grab the username of the entity who posted the photo.
        try:
            NameDivContainer = findall(r'<div class="lfloat _ohe fsm fwn fcg">(.*)</div>', content)
            NameLinkContainer = findall(r'<a href="https://www.facebook.com/(.*)\?fref=photo&amp;sk=photos">', NameDivContainer[0])
            UNAME = findall(r'https://www.facebook.com/.*', NameLinkContainer[0])
            name = UNAME[0].replace('https://www.facebook.com/', '')
            return name
        except IndexError:
            try:
                NE = findall(r'<div class="lfloat _ohe fsm fwn fcg">(.*)</div>', content)
                name = findall(r'<a href="https://www.facebook.com/(.*)\?fref=photo&amp;sk=photos">', NE[0])
                return name[0]
            except IndexError:
                try:
                    POC = findall(r'"actorid":.*?,', content)
                    ID = POC[0].replace('"actorid":', '').replace(',', '').replace('"', '')
                    APIUL = self.api + ID
                    IDN = self.GetHTTPRequest(APIUL).json()['username']
                    return IDN
                except KeyError:
                    UIDN = self.ProfileLink(content)
                    return UIDN

    def PhotoAlbum(self, content):

        """
        Attempt to determine what type of Facebook Photo Album we are pulling said information from.
        """

        PFNC = findall(r'<title id="pageTitle">.*?</title>', content, DOTALL) # Extract type, Base of all extraction types.
        PPANC = findall(r'Profile.*?Pictures', PFNC[0], DOTALL) # Grabs the name "Profile Pictures", Standard album name.
        CPANC = findall(r'Cover.*?Photos', PFNC[0], DOTALL) # Grabs the name "Cover Photos", Standard album name.
        MUANC = findall(r'Mobile.*?Uploads', PFNC[0], DOTALL) # Grabs the name "Mobile Uploads", Standard album name.
        TPANC = findall(r'Timeline.*?Photos', PFNC[0], DOTALL) # Grabs the name "Timeline Photos", Standard album name.
        IPANC = findall(r'Instagram.*?Photos', PFNC[0], DOTALL) # Grabs the name "Instagram Photos", Standard album name.
        iOSANC = findall(r'iOS.*?Photos', PFNC[0], DOTALL) # Grabs the name "iOS Photos", Standard album name.
        RANCRIGHT = findall(r' - .* \| ', PFNC[0]) # Grabs misc Album name, non-standard album name.
        RANCLEFT = findall(r'<title id="pageTitle">.*? - ', PFNC[0]) # Grab misc Album name, non-standard album name.

        if PPANC != []:
            return notifications.ALBUM + PPANC[0] # Profile Pictures album status

        # Cover Photos album status set
        if CPANC != []:
            return notifications.ALBUM + CPANC[0] # Cover Photos album status

        # Mobile Uploads album status set
        if MUANC != []:
            return notifications.ALBUM + MUANC[0] # Mobile Uploads album status

        # Timeline Photos album status set
        if TPANC != []:
            return notifications.ALBUM + TPANC[0] # Timeline Photos album status

        # Instagram Photos album status set
        if IPANC != []:
            return notifications.ALBUM + IPANC[0] # Instagram Photos album status

        # iOS Photos album status set
        if iOSANC != []:
            return notifications.ALBUM + iOSANC[0] # iOS Photos album status

        # If the Type of album is on the right handside of the title of the HTML.
        if "Profile Pictures" or "Cover Photos" or "Mobile Uploads" or "Timeline Photos" or "Instagram Photos" or "iOS Photos" not in RANCRIGHT[0]:
            return notifications.ALBUM + RANCRIGHT[0].replace(' | ', '').replace(' - ', '')

        # If the Type of album is on the left handside of the title of the HTML.
        if "Profile Pictures" or "Cover Photos" or "Mobile Uploads" or "Timeline Photos" or "Instagram Photos" or "iOS Photos" not in RANCLEFT[0]:
            return notifications.ALBUM + RANCRIGHT[0].replace('<title id="pageTitle">', '').replace(' - ', '')
