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

# 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() + "\\test.txt"
destination = os.getcwd() + "\\output\\results.txt"
#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
flag= 0
def metrics (user):
    try:
        user = str(user)
        URL = endpoint +user
        print(URL)
        head = {
            'Client-ID' : Client_ID,
            'Authorization' :  "Bearer " + access_token
            }
        response = requests.get(URL, headers=head)
        if response.status_code == 400:
            global flag
            flag= 1
        return flag, response.json()
    except:
        print("Failed and skipping...")
        
with open(origin, 'r', encoding='utf-8') as f1:
    userlist= [user.rstrip() for user in f1]
    for user in userlist:
        print(counter)
        flag, json_response = metrics(user)
        if flag == 1:
            print("flag")
            counter= counter+1
            flag= 0
        else:
            json_response = json_response['total']
            address= os.getcwd()+"\\output\\"+str(counter)+".txt"
            matrix= [[user,json_response]]
            print(matrix)
            with open(address, 'w', newline='', encoding='utf-8') as f2:
                writer= csv.writer(f2, delimiter=';')
                writer.writerow(matrix)               
                json_response = None
                counter= counter+1
            f2.close()
f1.close()

# joining txt obtained into one file
read_files = glob.glob(os.getcwd()+'\\output\\*.txt')

with open(destination, "w") as outfile:
    for n in read_files:
       with open(n) as infile:
           for line in infile:
               outfile.write(line)  
        
print('Thanks for using iMetrics Lab technologies')
