import requests
from requests.auth import HTTPBasicAuth
import time
import os
import json
from dotenv import load_dotenv

ENV_DIR = os.path.dirname(os.path.abspath(__file__))
#print("##.env url is: "+ ENV_DIR + "/.env")
load_dotenv(ENV_DIR + "/.env")
api_endpoint_start_from = "https://api.planningcenteronline.com/services/v2/songs?offset=0"
api_endpoint = "https://api.planningcenteronline.com/services/v2/songs/?per_page=25"
api_endpoint_person = "https://api.planningcenteronline.com/explorer/services/v2/people/"

#username = os.getenv('username')
#password = os.getenv('password')
username = os.environ.get('username')
password = os.environ.get('password')

#print(f"##username is: {password}")

def request_endpoint(endpoint):
    """
    Function for requesting data from Planning Center API
    Checks if the request-rate-limit is reached
    :param - URL to API endpoint to call
    :return - full response object
    missing - error handling in case of issues with API call
    """
    
    response = requests.get(endpoint, auth=HTTPBasicAuth(username, password))
    current_rate_count = response.headers.get('X-PCO-API-Request-Rate-Count')
    rate_periode = response.headers.get('X-PCO-API-Request-Rate-Period')
    rate_limit = response.headers.get('X-PCO-API-Request-Rate-Limit')
    
    if(current_rate_count is not None and int(current_rate_count) > (int(rate_limit)-10)):
        print ("### current rate count - " + current_rate_count + " rate periode - " + rate_periode+ " rate limit - " + rate_limit)
    
    """
    API returns 429 if rate_limit is reached
    I have not reached this treeshold from Norway, so the function has not been tested. But should work :-)
    """
    if response.status_code == 429:
        retry_after = response.headers.get('Retry-After')
        print ("### rate count reached - sleeping for: " + retry_after + " second")
        time.sleep(int(retry_after))
        response = requests.get(endpoint, auth=HTTPBasicAuth(username, password))
    
    return response
    #else:
    #    print("Error in API request:", response.status_code, response.text)

def request_song(song_id):
    api_endpoint_song = "https://api.planningcenteronline.com/services/v2/songs/"+ song_id
    print (api_endpoint_song)
    song_data_response = request_endpoint(api_endpoint_song)
    #print(json.dumps(song_data_response))
    return song_data_response.json()

def request_arrangment(song_id, arrangement_id):
    api_arrangemnt_url = "https://api.planningcenteronline.com/services/v2/songs/" + song_id + "/arrangements/" + arrangement_id
    #print (api_arrangemnt_url)
    response_arrangement_data = request_endpoint(api_arrangemnt_url)
    return response_arrangement_data.json()
