#!/usr/bin/python3
import json, os, glob
import subprocess
from subprocess import call
from subprocess import check_output
 
import requests 
# from http import request, json.dumps

def get_snapshots():
    """
    Get a list of snapshots.

    Returns:
        tuple: A tuple containing the JSON response and the status code.
    """

    try:
        # Define the file directory and path
        f_dir = '/home/fazle/WS/btc_rpc/bitnodesBtc-02/bitnodes/data/export/f9beb4d9/'

        # Get a list of JSON files in the directory
        f_list = glob.glob(f'{f_dir}*.json')
        f_list.sort(reverse=True)

        # Extract relevant information from the data based on the query parameters
        limit = min(max(int(requests.args.get('limit', default=10)), 10), 100)
        page = int(requests.args.get('page', default=1))

        # Validate the limit parameter type
        if not isinstance(limit, int):
            raise TypeError("Limit must be an integer")

        # Validate the page parameter type
        if not isinstance(page, int):
            raise TypeError("Page must be an integer")

        # Calculate the total number of pages
        total_snapshots = len(f_list)
        total_pages = (total_snapshots + limit - 1) // limit

        # Validate the page parameter
        if page < 1 or page > total_pages:
            raise ValueError("Invalid page number")

        # Calculate the start and end indices for the current page
        start_index = (page - 1) * limit
        end_index = start_index + limit

        # Create a list of snapshot results for the current page
        results = []
        for fpath in f_list[start_index:end_index]:
            entry = {}
            entry["timestamp"] = os.path.basename(fpath).removesuffix(".json")
            entry["url"] = f"http://127.0.0.1:5000/api/v1/snapshots/{entry['timestamp']}/"

            with open(fpath, 'r') as file:
                data = json.load(file)
                entry["total_nodes"] = len(data)
                entry["latest_height"] = data[-1][6]

            results.append(entry)

        # Create the API response dictionary
        response = {
            "count": total_snapshots,
            "results": results
        }

        # Add the "next" field to the response if there is a next page
        if page < total_pages:
            next_page = page + 1
            next_limit = "" if limit <= 10 else f"&limit={limit}"
            response["next"] = f"http://127.0.0.1:5000/api/v1/snapshots/?page={next_page}{next_limit}"
            print(limit)
        else:
            response["next"] = None

        # Add the "previous" field to the response if there is a previous page
        if page > 1:
            previous_page = page - 1
            previous_limit = "" if limit <= 10 else f"&limit={limit}"
            response["previous"] = f"http://127.0.0.1:5000/api/v1/snapshots/?page={previous_page}{previous_limit}"
        else:
            response["previous"] = None

        return json.dumps(response), 200

    except TypeError as e:
        error_response = {"error": str(e)}
        return json.dumps(error_response), 400

    except ValueError as e:
        error_response = {"error": str(e)}
        return json.dumps(error_response), 400

    except Exception as e:
        error_response = {"error": "An error occurred while processing the request"}
        return json.dumps(error_response), 500


if (len(sys.argv) < 2):
    print("Usage: listNodes.py numberOfnodes \n")
    exit()
nodes = int(sys.argv[1])

jsonFile = open("/home/fazle/WS/btc_rpc/bitnodesBtc-02/bitnodes/data/export/f9beb4d9/1687092052.json")
nodeList = json.load(jsonFile)
print(get_snapshots()  )

jsonFile.close()


