# -*- coding: utf-8 -*-
"""
Created on January 2023
@author: Enrique Orduña-Malea
"""
import requests
import json
import time
import os
import glob

# add your customised query; login and id are excluyent.
access_token= "insert your access token"
Client_ID= "insert your client-ID"
#login= "insert here""
#id="insert here"

origin= os.getcwd() + "\\data.txt"
destination = os.getcwd() + "\\results.json"
#endpoint="https://api.twitch.tv/helix/users?id="
#endpoint="https://api.twitch.tv/helix/users?login="
endpoint="https://api.twitch.tv/helix/users/follows?to_id="
#endpoint="https://api.twitch.tv/helix/channels?broadcaster_id="
#endpoint="https://api.twitch.tv/helix/goals?broadcaster_id="
#endpoint="https://api.twitch.tv/helix/bits/cheermotes?broadcaster_id="
#endpoint="https://api.twitch.tv/helix/chat/emotes?broadcaster_id="
#endpoint="https://api.twitch.tv/helix/clips?broadcaster_id="
#endpoint="https://api.twitch.tv/helix/games?id="

counter=1

def metrics (user):
    user = str(user)
    URL = endpoint +user
    print(URL)
    head = {
    'Client-ID' : Client_ID,
    'Authorization' :  "Bearer " + access_token
    }

    time.sleep(1)
    response = requests.get(URL, headers=head)
    return response.json()
    
with open(origin, 'r', encoding='utf-8') as f1:
    userlist= [user.rstrip() for user in f1]
    for user in userlist:
        print(counter)
        json_response = metrics(user)
        json_response = json_response['data']
        address= os.getcwd()+"\\"+str(counter)+".json"
        with open(address, 'w', newline='', encoding='utf-8') as f2:
            json.dump(json_response, f2, indent=4)
            json_response = None
        counter= counter+1
        f2.close()
f1.close()

# joining json obtained into one file in final.csv
glob_data = []
for file in glob.glob(os.getcwd()+'\\*.json'):
    with open(file) as json_file:
        data = json.load(json_file)

        i = 0
        while i < len(data):
            glob_data.append(data[i])
            i += 1
with open(destination, 'w') as f:
    json.dump(glob_data, f, indent=4)
    
print('Thanks for using iMetrics Lab technologies')
