# ------------------------------------------------------------
# insertnodes.py - replace 
# ------------------------------------------------------------

from browser import document as doc
from browser import window
from utils import *

# ------------------------------------------------------------

g.fetches = 0

# ------------------------------------------------------------

def replace_icons (root = none) :
	'replace all <icon> tags with svg elements directly'

	if root is none :  root = doc

	icons = root.querySelectorAll ('icon')
	log (f'replacing icons : { len (icons) }')

	for icon in list (icons) :
		url = icon.attrs.get ('src', '')
		if not url : continue

		do_icon (icon, url)

# ------------------------------------------------------------

def startfetch () :
	'track fetch operations to completion'

	g.fetches += 1

# ---

def fetchdone (dummy = -1) :
	'mark fetch operation as done'

	log (f'one fetch done : { g.fetches } : { type (dummy) } : { dummy }')

	g.fetches -= 1
	if g.fetches == 0 :  
		log (f'all fetches done')
		signaldone ()

# ------------------------------------------------------------

def on_error (err) :
	warn (f'fetch error : { err }')
	fetchdone ()

# ------------------------------------------------------------

def do_icon (icon, url) :
	'fetch and replace a single <icon> tag'

	def on_text (text) :
		svg = window.DOMParser.new ().parseFromString (text, 'image/svg+xml').documentElement
		for attr in icon.attributes :
			svg.setAttribute (attr.name, attr.value)

		svg.classList.add ('icon')
		icon.parentNode.replaceChild (svg, icon)
		fetchdone ()

	def on_resp (resp) :
		#resp.text ().then (on_text)
		if resp.ok :
			resp.text ().then (on_text)
		else :
			warn (f'snippet fetch failed { url } : { resp.status }')
			fetchdone ()

	startfetch ()
	window.fetch (url).then (on_resp).catch (on_error)

# ------------------------------------------------------------

def replace_snippets () :
	'replace all <snippet> tags with retrieved src'

	snippets = doc.querySelectorAll ('snippet')
	log (f'replacing snippets : { len (snippets) }')

	for snip in list (snippets) :
		url = snip.attrs.get ('src', '')
		if not url : continue

		do_snippet (snip, url)

# ------------------------------------------------------------

def do_snippet (snip, url) :
	'fetch and replace a single <snippet> tag'

	def on_text (text) :

		log (f'got snippet, inserting : { url }')
		wrap = doc.createElement ('div')
		wrap.innerHTML = text

		root = wrap.firstElementChild
		if not root : return

		for attr in snip.attributes :
			if attr.name != 'src' :
				root.setAttribute (attr.name, attr.value)

		# replace icons in snippet
		replace_icons (root)

#		# turn off element temporarily
		origdisp = root.style.display
		root.style.display = 'none'

		snip.parentNode.replaceChild (root, snip)

		# revert back display value after a small delay
		# this allows browser to insert & paint before we remove display style

		def revert () :
			root.style.display = origdisp
		window.setTimeout (revert, 0.5 * SEC)
#		root.style.display = origdisp

		log (f'snippet done : { url }')
		fetchdone ()

	def on_resp (resp) :
		#resp.text ().then (on_text)
		if resp.ok :
			resp.text ().then (on_text)
		else :
			warn (f'snippet fetch failed { url } : { resp.status }')
			fetchdone ()

	startfetch ()
	now = int (window.Date.now () / 10000)
	window.fetch (url + f'?t={ now }').then (on_resp).catch (on_error)

# ------------------------------------------------------------

def activate_tabs (root = none) :
	'attach tab-switching click handlers to all nav.tabs found in root'

	if root is none : root = doc
	DEBUG and log (f'checking for nav.tabs...')

	for nav in root.querySelectorAll ('nav.tabs') :
		DEBUG and log (f'found nav.tabs')
		card = nav.closest ('section.card')
		if not card :
			warn (f'activate_tabs : nav.tabs has no ancestor section.card')
			continue
		for item in nav.querySelectorAll ('li') :
			attach_tab (item, nav, card)

	log (f'activate_tabs : done')

# ------------------------------------------------

def attach_tab (item, nav, card) :
	'attach click handler to single tab li'

	def on_click (evt) :
		tabclasses = [ c for c in item.classList if c != 'active' ]

		for other in nav.querySelectorAll ('li') :
			other.classList.remove ('active')
			for c in [ c for c in other.classList if c != 'active' ] :
				card.classList.remove (c)

		item.classList.add ('active')
		for c in tabclasses :
			card.classList.add (c)

		log (f'tab : activated : { tabclasses }')

	item.addEventListener ('click', on_click)

# ------------------------------------------------------------

def signaldone () :
	'signal when all nodes fetched.  DOESNT WORK too fragile async ops'
	window.NODES_READY = true
	evt = window.CustomEvent.new ('nodes-ready')
	doc.dispatchEvent (evt)

# ------------------------------------------------------------

def main () :

	activate_tabs ()

	pending = [ 0 ]   # number of pending insertions

	# replace snippets first so icons inside get replaced after
	replace_snippets ()
	replace_icons ()

# ------------------------------------------------------------

try :  main ()
except Exception as e :  shout (f'error in main : { e }')

