import datetime, requests

from threatingestor.sources import Source
import threatingestor.artifacts

def user_set(user):
    GIST_SEARCH_URL = "https://api.github.com/users/{0}/gists".format(user)
    return GIST_SEARCH_URL

class Plugin(Source):
    """Github Gist Source Plugin"""
    def __init__(self, name, user="", username="", token=""):
        self.name = name
        self.user = user

        if username and token:
            self.auth = (username, token)
        else:
            self.auth = None

    def _gist_search(self, params):
        """Returns a list of gist results."""
        
        # Iterates through pages of results from query.
        response = requests.get(user_set(self.user), params=params, auth=self.auth)

        gist_list = []

        for gist in response.json():
            gist_list.append(gist)

        return gist_list

    def run(self, saved_state):
        """Returns a list of artifacts and the saved state"""

        params = { "per_page": "100" }

        saved_state = datetime.datetime.utcnow().isoformat()[:-7] + 'Z'
        gist_list = self._gist_search(params)

        artifact_list = []
        
        for gist in gist_list:
            title = "Gist Owner: {0}".format(self.user)
            description = 'URL: {u}\nTask autogenerated by ThreatIngestor from source: {s}'
            description = description.format(s=self.name, u=gist['html_url'])
            artifact = threatingestor.artifacts.Task(title, self.name, reference_link=gist['html_url'], reference_text=description)

            artifact_list.append(artifact)

        return saved_state, artifact_list