# /intranet-leaflet/lib/leaflet-crm-ip-component.tcl
#
# Variables from page:
#
# width
# height

if {![info exists width]} { set width 600 }
if {![info exists height]} { set height 400 }

# template::head::add_css -href "https://unpkg.com/leaflet@1.3.3/dist/leaflet.css" -media "screen" -order 100
# template::head::add_javascript -src "https://unpkg.com/leaflet@1.3.3/dist/leaflet.js" -order 200
template::head::add_css -href "/intranet-leaflet/resources/leaflet.css" -media "screen" -order 100
template::head::add_javascript -src "/intranet-leaflet/resources/leaflet.js" -order 200

set zoom_lat [parameter::get_from_package_key -package_key "intranet-leaflet" -parameter ZoomLatitude -default "41.4"]
set zoom_lng [parameter::get_from_package_key -package_key "intranet-leaflet" -parameter ZoomLongitude -default "2.2"]
set zoom_zoom [parameter::get_from_package_key -package_key "intranet-leaflet" -parameter ZoomZoom -default "3"]

set ip_sql "
	select	'blue' as color,
		ip.cnt,
		c.code as country_code,
		c.country as country_name,
		c.lat as geo_lat,
		c.lon as geo_lng
	from	(select	count(*) as cnt,
			n.country
		from	(select	*,
				(split_part(ao.creation_ip, '.', 1)::bigint << 24) +
		      		(split_part(ao.creation_ip, '.', 2)::bigint << 16) +
				(split_part(ao.creation_ip, '.', 3)::bigint << 8) +
				(split_part(ao.creation_ip, '.', 4)::bigint) as ip_address
			from	acs_objects ao
			where	ao.creation_ip is not null and 
				ao.creation_ip != '127.0.0.1' and
				ao.creation_ip not like '192.168.%' and
				ao.creation_ip not like '172.26.%' and
				ao.creation_ip ~ '^\[0-9\]+\.\[0-9\]+\.\[0-9\]+\.\[0-9\]+$' and
				length(ao.creation_ip) > 7
			) o
			join ip2nation n on ip = (select max(ip) from ip2nation where ip_address > ip)
		group by
			n.country
		) ip
		LEFT join ip2nationcountries c on c.code = ip.country
"

#ad_return_complaint 1 [im_ad_hoc_query -subtotals_p 0 -format html $ip_sql]

set store [lindex [im_sencha_sql_to_store -sql $ip_sql] 0]

