#!/usr/bin/perl -w

# rank_hourly.pl
# (c) CWZ, LLC

# Reset the hourly reference value for Rankings

use strict;
use lib '.';
use CWZ;

Exec: {
    # Wait a few seconds to make sure other updates complete
   #sleep(5);

	# Tax the runners
	# SELECT AVG(tot_val) FROM Toon_Value WHERE tot_val > 1_000_000
	# SELECT * FROM Toon WHERE tot_val > 1_000_000_000 AND tot_val > avg_val * 2
	# LOOP to update.. subtracting a progressive tax of hourly increase up to 90% (at 10x avg_val) and accumulate the value in tax_revenue
	#
	# SELECT COUNT() FROM Toon WHERE tot_val > 1_000_000 AND tot_val < avg_val * 2 AND turns < 5000 AND bank < 1_000_000_000
	# divide tax_renevue by COUNT() = tax_redist
	# UPDATE Toon SET bank = bank + tax_redist

	# Reset gang value hourly reference
	qDb_do("UPDATE Squad_Rank SET hourly_ref = value, hourly_pct = 0");

	# Decrease outs by 3 per hour
	qDb_do("UPDATE Player SET outs = GREATEST(outs - 3, 0), ins = GREATEST(ins - 3, 0)");

	# Reset hourly crypto price reference
	qDb_do("UPDATE Crypto_Game SET price_ref = price_now");
	qDb_do("UPDATE Crypto_Live SET price_ref = price_now");

	# Country Bonus
	#foreach ( qw(use_rank usw_rank mex_rank col_rank rus_rank hk_rank can_rank aus_rank) ) {

	#}


	# Delete console stuff older than several days
	# ..maybe move to a history (ConsoleHist) table? (and just chat content))
	#qDb_do("DELETE FROM Console WHERE ts < (NOW() - INTERVAL 7 DAY) AND id <> 0");

	# Delete chat log whitespace only entries after a day
	qDb_do(q/DELETE FROM Chat WHERE ts < (NOW() - INTERVAL 1 DAY) AND msg REGEXP ':[[:space:]]$'/);

	# Delete attacks older than 2 days
	#qDb_do("DELETE FROM Attack_Log WHERE ts < (NOW() - INTERVAL 2 DAY)");

	# Clear old TwelveLog entries
	#qDb_do("DELETE FROM TwelveLog WHERE exp < UNIX_TIMESTAMP()");


  #Update Ins Every Hour
    qDb_do("UPDATE Player
    SET ins = (
      SELECT COUNT(defender)
      FROM Attack_Log
      WHERE defender = Player.charnm
        AND timestamp >= NOW() - INTERVAL 24 HOUR)");

	#Bonus turns for boosted players
		qDb_do("UPDATE Player AS p
            LEFT JOIN Boosts AS b1 ON p.login_id = b1.login AND b1.package = 1
            LEFT JOIN Boosts AS b2 ON p.login_id = b2.login AND b2.package = 2
            SET p.turns = p.turns +
              CASE
                  WHEN b1.package = 1 AND b2.package = 2 THEN 10
                  WHEN b1.package = 1 THEN 5
                  WHEN b2.package = 2 THEN 5
                  ELSE 0
              END");

			#Clear Out Crypto History
			qDb_do("UPDATE Crypto_Live_History
				SET price_history = SUBSTRING_INDEX(price_history, ',', 144)
				WHERE INSTR(price_history, ',') > 0;");
			qDb_do("UPDATE Crypto_Game_History
				SET price_history = SUBSTRING_INDEX(price_history, ',', 144)
				WHERE INSTR(price_history, ',') > 0;");
}
