#!/usr/bin/env python

import anti_config
import anti_download
import asyncio
import datetime
import sys
import telethon
import traceback

# back to normal: sys.stdout = sys.__stdout__

# DEBUG = False
DEBUG = True

DO_POST = False
# DO_POST = True

# SINGLE_URL = False
SINGLE_URL = True

def log_open():
	logfp = open( "anti_bot.log", "w" )
	sys.stdout = logfp

def log_close():
	logfp = sys.stdout
	# back to normal:
	sys.stdout = sys.__stdout__

def log_timestamp( text ):
	ts = datetime.datetime.today().strftime( "%Y-%m-%d %H:%M:%S" )
	print( "%s: %s" % ( ts, text ) )
	sys.stdout.flush()

async def download_and_send( client, urls, url, seconds_until_poll ):
	i = 0
	for msg in data:
		i += 1
		nofm = "[%d/%d]" % ( i, len(data) )
		if type(msg) is tuple and msg[0] == 'img':
			# send image URL
			print( "img:", msg[1] )
			if DO_SEND:
				try:
					await client.send_file( anti_config.destination, msg[1] )
				except:
					log_timestamp( "caught exception from send_file" )
					print( "client.send_file( %s, %s )" % (
							anti_config.destination, msg[1] ) )
					traceback.print_exc()
		else:
			# send text message
			text = msg + "\n\n" + nofm 
			print( "txt %s:" % nofm, text[:60] )
			if DEBUG:
				print( ">>>>%s<<<<" % text )
			if DO_SEND:
				try:
					await client.send_message( anti_config.destination, text )
				except:
					log_timestamp( "caught exception from send_message" )
					print( "client.send_message( %s, %s )" % (
							anti_config.destination, text ) )
					traceback.print_exc()
		await asyncio.sleep( anti_config.send_delay_s )
		seconds_until_poll -= anti_config.send_delay_s
	urls.url_done( url )
	log_timestamp( "url done." )
	await asyncio.sleep( anti_config.post_delay_s )
	seconds_until_poll -= anti_config.post_delay_s
	return seconds_until_poll

async def bot_main( client ):

	print( "**** bot_main ****" )

	urls = anti_download.URLs( anti_config.base_url, anti_config.url_file )

	seconds_until_poll = 0
	while client.is_connected():

		# time to poll for new URLs?
		if seconds_until_poll <= 0:
			log_timestamp( "poll website" )
			seconds_until_poll += anti_config.poll_period_s
			await anti_download.check_for_new_urls( urls )

		# do we have new URLs to download?
		if urls.has_new_url():
			# have new URLs to download
			log_timestamp( "download URL" )
			url = urls.next_new_url()
			print( "url:", url )
			# webpage = await load( url, anti_config.cache_dir )
			webpage = await anti_download.download_url( url )
			print( "download:", webpage[0] )
			if webpage[0] == 200:
				data = anti_download.filter_html( webpage[2], webpage[3] )
			if SINGLE_URL:
				break
		else:
			# no new URLs, sleep until next poll
			await asyncio.sleep( seconds_until_poll )

	print( "**** bot_main ended ****" )


async def main():
	client = telethon.TelegramClient( 'bot',
				anti_config.api_id, anti_config.api_hash )
	await anti_download.init_cookies()
	await client.start( bot_token=anti_config.bot_token )
	client.loop.create_task( bot_main( client ) )
	await client.run_until_disconnected()

if __name__ == "__main__":
	log_open()
	try:
		asyncio.run( main() )
	except:
		log_timestamp( "caught exception from main()" )
		traceback.print_exc()
	log_close()

