import json
import requests
import time
import click
import math
from multiprocessing import Queue
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    
# Get parameters to watch
@click.command()
@click.option('--chan', prompt='Imageboard to target (4chan/8chan/76chan)', help='Imageboard to target (4chan/8chan/76chan)')
@click.option('--board', prompt='Board to target', help='Board to target')
@click.option('--get', prompt='Target GET', help='Target GET')
def main(chan, board, get):
    print("=== TARGETING POST {0} ON {1} /{2}/ ===".format(get,chan,board))

    start_time = time.time()
    maxno = 0
    startingvalue = 0
    while True:
        # Look up json posts
        if chan == "4chan":
            r = requests.get("http://api.4chan.org/{0}/1.json?t={1}".format(board,time.time()))
        elif chan == "8chan":
            r = requests.get("http://8ch.net/{0}/0.json?t={1}".format(board,time.time()))
        elif chan == "76chan":
            r = requests.get("https://76chan.org/{0}/0.json?t={1}".format(board,time.time()), verify=False)
        try:
            # Loop through every post and find max
            posts = r.json()
            for thread in posts['threads']:
                for post in thread['posts']:
                    if post['no'] > maxno:
                        maxno = post['no']
            # Find number of posts left (get - current post number)
            poststo = int(get) - maxno

            if startingvalue == 0:
                startingvalue = maxno

            # Exit program if GET has already happened
            if poststo < 0:
                print("The GET has passed! Good luck! :^)")
                input('Press enter to exit...')
                break

            # Estimated time calculation
            if startingvalue is not maxno:
                timeelapsed = time.time() - start_time #seconds
                postsincestart = maxno - startingvalue # postscalc
                gettime = poststo / postsincestart * timeelapsed / 60
                gettime = int(round(gettime))
                if gettime < 60:
                    if gettime == 1:
                        t = str(gettime) + " Minute"
                    else:
                        t = str(gettime) + " Minutes"
                else:
                    hours = int(math.floor(gettime / 60))
                    remainder = gettime % 60
                    if hours == 1:
                        t = str(hours) + " Hour "
                    else:
                        t = str(hours) + " Hours "
                    if remainder == 1:
                        t += str(remainder) + " Minute"
                    else:
                        t += str(remainder) + " Minutes"
                print("{0} until {1} - Estimated Time: {2}".format(poststo, get, t))

                # Recalculate post time every so often (should I lower or make configurable?)
                if timeelapsed > 300:
                    print("Recalculating time...")
                    start_time = time.time()
                    startingvalue = maxno
            else:
                # Alert users of the current post count
                print("{0} until {1}".format(poststo, get))

        # This is a list of errors I've encountered while running. Usually because the website did not return any json or was down due to stress (large 8ch boards)
        # If hit just continue from the start of the while loop
        except (IndexError, ValueError, KeyError, requests.exceptions.ConnectionError, requests.exceptions.ChunkedEncodingError):
            print("Error - Most likely from website retuning bad data. Continuing")
            pass

        # Wait one second before starting again
        time.sleep(1)
        
if __name__ == '__main__':
    main()