# /intranet-leaflet/lib/leaflet-world-countries.tcl
#
# Variables from page:
#
# width
# height
# year

im_sencha_extjs_load_libraries
ad_proc im_tmp_table_exists { table } {
    set lock_exists_p [db_string lock_exists_p "
    select count(*) FROM pg_catalog.pg_class c LEFT JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace
    where n.nspname like 'pg_temp_%' AND pg_catalog.pg_table_is_visible(c.oid) and 
    upper(relname) = upper(:table)
    "]
    if {$lock_exists_p > 0} { return 1 } else { return 0 }
}

set message ""

if {![info exists width]} { set width 600 }
if {![info exists height]} { set height 400 }
if {![info exists year]} { set year [db_string year "select to_char(now(), 'YYYY')"] }

# 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 aggr "tmp_crm_online_interactions_aggregate"
set lock "tmp_crm_online_interactions_aggregate_lock"
set lock_exists_p [db_table_exists tmp_crm_online_interactions_aggregate_lock]
set aggr_exists_p [db_table_exists tmp_crm_online_interactions_aggregate_country]
if {$lock_exists_p > 1} { set lock_exists_p 1 }
if {$aggr_exists_p > 1} { set aggr_exists_p 1 }

# Dummy SQL
set ip_sql "
	select	'blue' as color,
		0 as cnt,
		'nn' as country_code,
		'None' as country_name,
		0.0 as geo_lat,
		0.0 as geo_lng
"


set switch_string "$lock_exists_p-$aggr_exists_p"
# ad_return_complaint 1 "switch_string=$switch_string<br>lock=[db_table_exists tmp_crm_online_interactions_aggregate_lock]<br>aggr=[db_table_exists tmp_crm_online_interactions_aggregate]<br>"


set switch_string "1-1"

switch $switch_string {
    "0-0" {
	# No lock and no aggr

	set message "<b>Aggretating Data - Please wait for ~1 minute</b><br>&nbsp;<br>
		     Please wait for approx 1 minute and try again.<br>
		     Our system will need this time in order to perform<br>
		     some complex operations. ($switch_string)
	"

	im_report_write_http_headers -output_format html
        ns_write "
        [im_header "Agregating Data - Please wait"]
        [im_navbar crm]
        <p>$message</p>
	[im_footer]
        "

	# IP2Nation: Unknown addresses will become zz instead of US
	db_dml ip2nationzz "update ip2nation set country = 'zz' where ip = 0"


	db_dml drop_lock "drop table if exists tmp_crm_online_interactions_aggregate_lock"
	db_dml drop_aggr "drop table if exists tmp_crm_online_interactions_aggregate"
	db_dml drop_coun "drop table if exists tmp_crm_online_interactions_aggregate_country"
	# Create main aggregration, extracting only IP, month and interaction_type from crm_online_interactions
	db_dml create_lock {
	        create table tmp_crm_online_interactions_aggregate_lock as select now() as today
	}
	db_dml create_aggr {
		create	table tmp_crm_online_interactions_aggregate as
		select	count(*) as cnt,
			t.interaction_type_id,
			t.year_month,
			trim(t.ip_address) as ip_address
		from	(select	interaction_type_id,
				to_char(interaction_date, 'YYYY-MM') as year_month,
				ip_address
			from	crm_online_interactions
			-- LIMIT 20000
			) t
		group by
			interaction_type_id, year_month, ip_address
        }
	db_dml create_aggr_country {
		create	table tmp_crm_online_interactions_aggregate_country as
		select	sum(o.cnt) as cnt,
			o.interaction_type_id,
			o.year_month,
			n.country
		from	(select	coi.interaction_type_id,
				coi.cnt,
				coi.year_month,
				(split_part(coi.ip_address, '.', 1)::bigint << 24) +
				(split_part(coi.ip_address, '.', 2)::bigint << 16) +
				(split_part(coi.ip_address, '.', 3)::bigint << 8) +
				(split_part(coi.ip_address, '.', 4)::bigint) as ip_address
			from	tmp_crm_online_interactions_aggregate coi
			where	coi.ip_address is not null and
				coi.ip_address not in ('0.0.0.0', '127.0.0.1') and
				coi.ip_address not like '192.168.%' and
				coi.ip_address not like '172.26.%' and
				coi.ip_address ~ '^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$' and
				length(coi.ip_address) > 7
			) o
			join ip2nation n on ip = (select max(ip) from ip2nation where ip_address > ip)
		group by n.country, o.interaction_type_id, o.year_month
        }	
	ad_script_abort
    }
    "1-0" {
	# Lock exists but no aggregation yet - wait!
	set message "<b>Aggretating Data - Please wait for ~1 minute</b><br>&nbsp;<br>
		     Aggregation has already started.<br>
                     Please wait for approx 1 minute and try again.<br>
		     Our system will need this time in order to perform<br>
		     some complex operations.
	"
    }
    "0-1" - "1-1" {
	# Aggregation exists
	set ip_sql "
        select  'blue' as color,
                ip.cnt as cnt,
                c.code as country_code,
                c.country as country_name,
                c.lat as geo_lat,
                c.lon as geo_lng
	from	(
			select	sum(cnt) as cnt,
				country
			from
				tmp_crm_online_interactions_aggregate_country ip
			group by country
		) ip
                LEFT join ip2nationcountries c on c.code = ip.country
        "
    }
    default  {
	ad_return_complaint 1 "Invalid switch_string=$switch_string"
    }
}


#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]

set message ""
