import requests
import datetime as dt
import json
import os
from wrapt_timeout_decorator import *
import time 


key = os.environ.get('KKEXKEY')

def main(vcs, early_cutoff):
    time.sleep(1)
    gsql_dict = {}
    vcs_list = vcs.split('/')
    repo_name = '"' + vcs_list[-1] + '"'
    repo_owner = '"' + vcs_list[-2] + '"'
    gsql_dict["original_returned_content"] = get_discussion_gql(repo_owner, repo_name)
    gsql_dict["time_cleaned_comm"] = within_time(gsql_dict["original_returned_content"], early_cutoff)
    return gsql_dict['original_returned_content']

def get_discussion_gql(repo_owner, repo_name):
    url = "https://api.github.com/graphql"
    data_string = ("""
    query {
        repository(owner: """ + repo_owner + """, name: """ + repo_name + """) {
            issues(last: 50) {
                edges {
                    node {
                        id 
                        title
                        url
                        number
                        state
                        author {
                        login
                        url
                        }
                        labels(first:5) {
                            edges {
                                node {
                                name
                                }
                            }
                        }
                        comments(first: 20) {
                            # edges.node is where the actual `Comment` object is
                            edges {
                            node {
                                id
                                author {
                                    login
                                    url
                                }
                                body
                            }
                            }
                        }
                    body
                    }
                }
            }
        }
    }
    """)
    data =  {"query" : data_string}
    data_json = json.dumps(data)
    headers = {'content-type': 'application/json', 'Accept-Charset': 'UTF-8', 'Authorization': 'bearer ' + key}
    try:
        r = requests.post(url=url, data=data_json, headers=headers)
        print(r.content)
        return r.json()
    except:
        print("issue somewhere with getting gsql stuff")
        return {}

def within_time(comment_content, early_cutoff):
    try: 
        list_of_comments = json.loads(comment_content)["data"]["repository"]["discussions"]["edges"]
        valid_comments = []
        for comment in list_of_comments:
            if dt.datetime.fromisoformat(comment['node']['createdAt'][:-1]) < early_cutoff:
                break
            else:
                valid_comments.append(comment)
        return valid_comments
    except TypeError:
        print("no discussions found")
        return []
    

if __name__ == "__main__":
    repo_name = '"' + 'numpy' + '"'
    repo_owner = '"' + 'numpy' + '"'
    get_discussion_gql(repo_owner, repo_name)


# stashed info about page cursors 
'''            pageInfo {
            # type: PageInfo (from the public schema)
            startCursor
            endCursor
            hasNextPage
            hasPreviousPage
            }
'''

'''
issue(number: 2) {
      title
      createdAt
      # first 10 results
      comments(first: 10) {
        # edges.node is where the actual `Comment` object is
        edges {
          node {
            author {
              avatarUrl
            }
            body
          }
        }
      }
    }

'''

'''
    discussions(first: 10) {
                # type: DiscussionConnection
                totalCount # Int!
        
                edges {
                # type: DiscussionEdge
                cursor
                node {
                    # type: Discussion
                    id
                    title # String!
                    bodyText # String! 
                    createdViaEmail # Boolean!
                    createdAt # DateTime!
                    answer {
                        #type: DiscussionComment
                        bodyText # String!
                    } 
                    comments(first: 10){
                        # type: DiscussionCommentConnection
                        totalCount # Int!
                        edges {
                            # type: DiscussionCommentEdge
                            node {
                                # type: DiscussionComment
                                id
                                bodyText # String! 
                            }
                        
                        }
                    }
                }
                }
            }

'''