<?php

namespace WPDRMS\ASP\Index;

use WPDRMS\PluginCore\Interfaces\Registrable;

if ( !defined('ABSPATH') ) {
	die('-1');
}

class IndexTableHooks implements Registrable {
	public function register(): void {
		$worker = IndexTableWorker::instance();

		IndexService::scheduleSnapshotCron();
		add_action( 'asp_index_size_snapshot', array( IndexService::instance(), 'recordDailySnapshot' ) );

		add_action('edit_attachment', array( $worker, 'queueUpdate' ), 999999998, 3);
		add_action('add_attachment', array( $worker, 'queueUpdate' ), 999999998, 3);
		add_action('save_post', array( $worker, 'queueUpdate' ), 999999998, 3);
		add_action('wp_insert_post', array( $worker, 'queueUpdate' ), 999999999, 3);
		add_action('added_post_meta', array( $worker, 'queueUpdateFromMeta' ), 999999999, 2);
		add_action('updated_post_meta', array( $worker, 'queueUpdateFromMeta' ), 999999999, 2);
		add_action('delete_post', array( $worker, 'deleteDocument' ), 10, 1);
		add_action('asp_cron_it_extend', array( $worker, 'runCronBatch' ), 10, 0);
		add_action('wp_footer', array( $worker, 'flushQueue' ), 10, 0);
		add_action('admin_bar_menu', array( $worker, 'flushQueue' ), 10, 0);
		add_action('shutdown', array( $worker, 'flushQueue' ), 10, 0);

		$worker->scheduleCron();
	}

	public function deregister(): void {
		$worker = IndexTableWorker::instance();

		remove_action('edit_attachment', array( $worker, 'queueUpdate' ), 999999998);
		remove_action('add_attachment', array( $worker, 'queueUpdate' ), 999999998);
		remove_action('save_post', array( $worker, 'queueUpdate' ), 999999998);
		remove_action('wp_insert_post', array( $worker, 'queueUpdate' ), 999999999);
		remove_action('added_post_meta', array( $worker, 'queueUpdateFromMeta' ), 999999999);
		remove_action('updated_post_meta', array( $worker, 'queueUpdateFromMeta' ), 999999999);
		remove_action('delete_post', array( $worker, 'deleteDocument' ), 10);
		remove_action('asp_cron_it_extend', array( $worker, 'runCronBatch' ), 10);
		remove_action('wp_footer', array( $worker, 'flushQueue' ), 10);
		remove_action('admin_bar_menu', array( $worker, 'flushQueue' ), 10);
		remove_action('shutdown', array( $worker, 'flushQueue' ), 10);
	}
}
