#!/usr/bin/python3 -u

## Copyright (C) 2017 - 2023 ENCRYPTED SUPPORT LP <adrelanos@whonix.org>
## See the file COPYING for copying conditions.

import os
import time
import datetime
from sdwdate.remote_times import get_time_from_servers
from sdwdate.config import read_pools
from sdwdate.proxy_settings import proxy_settings

proxy_ip, proxy_port = proxy_settings()

# Helpers for a cludge to check only 3 urls at once
def chunks(my_list, n):
    """Yield successive n-sized chunks from my_list."""
    for i in range(0, len(my_list), n):
        yield my_list[i:i + n]

def exec_curl(c_url):
    cmd = 'curl --head '+c_url+'> /dev/null 2>&1'
    c_out = os.system(cmd)
    if '0' in str(c_out) :
        return ' (Curl --head is OK)'
    else:
        return ' (Curl --head also Not OK)'

class Pool:
    def __init__(self, pool):
        self.urls, self.comments = read_pools(pool, 'test')

class CheckRemotes:
    def __init__(self):
        self.number_of_pools = 3
        self.pools = [Pool(pool) for pool in range(self.number_of_pools)]
        self.urls = []
        self.comments = []
        self.returned_values = []
        self.list_of_status = []
        self.list_of_unixtimes = []
        self.list_of_took_time = []
        self.list_of_half_took_time = []
        self.list_off_time_diff_raw_int = []
        self.list_off_time_diff_lag_cleaned_float = []

    def loop(self):
        time_stamp_ts = int(time.time())
        print ('Current Time: '+str(time_stamp_ts))

        print('Starting remotes check...')
        for pool in self.pools:
            #orig_list = pool.urls[:]
            #print ('Debug:'+str(type(pool.urls))+str(len(pool.urls)))
            #print('Debug:'+str(type(orig_list))+str(len(orig_list)))

            ## For avg
            tot_diff = 0

            ##print(pool.urls)
            ##print(list(chunks(pool.urls,3)))
            ##exit()
            self.list_of_urls_returned = list(chunks(pool.urls,3))
            for url_chunk in self.list_of_urls_returned:
                print("Testing the URL Chunk: ")
                print(url_chunk)

                self.list_of_urls_returned, \
                self.list_of_status, \
                self.list_of_unixtimes, \
                self.list_of_took_time, \
                self.list_of_half_took_time, \
                self.list_off_time_diff_raw_int, \
                self.list_off_time_diff_lag_cleaned_float, \
                   = get_time_from_servers(
                      self.pools,
                      url_chunk,
                      proxy_ip,
                      proxy_port
                   )

                for url in range(len(self.urls)):
                    #print('Debug:'+self.returned_values[url])
                    if 'Timeout' in str(self.returned_values[url]):
                        msg = 'pool %s url %s: %s' % (self.pools.index(pool) + 1, self.urls[url], self.returned_values[url])
                        msg += exec_curl(self.urls[url])
                    elif 'error' in str(self.returned_values[url]):
                        msg = 'pool %s url %s: %s' % (self.pools.index(pool) + 1, self.urls[url], (self.returned_values[url]).decode())
                        msg += exec_curl(self.urls[url])
                    elif 'Parsing' in str(self.returned_values[url]):
                        msg = 'pool %s url %s: %s' % (self.pools.index(pool) + 1, self.urls[url], self.returned_values[url])
                        msg += exec_curl(self.urls[url])
                    else:
                       msg = 'pool %s url %s: Time: %s Difference: %d' % (self.pools.index(pool) + 1, self.urls[url], (self.returned_values[url]).decode(), int(time.time()) - int(self.returned_values[url]))
                       tot_diff += abs(int(time.time()) - int(self.returned_values[url]))
                    print(msg)
                    f.write('%s\n' % msg)
                ## End For url in self.urls
            ## End For each URL Chunk
            avg = tot_diff/len(pool.urls)
            print("##############################")
            print("Avg of Pool :"+str(self.pools.index(pool)+1) +" having URLs #:"+ str(len(pool.urls)) +" is "+str(avg))
            print("##############################")
        ## End for each URL Pool (there are 3 such pools)

if __name__ == '__main__':
    remotes = CheckRemotes()
    remotes.loop()
