<?php
/**
 * Class Auto_Sync_Cron
 */

namespace BwWinnersGlobalSite\Sync;

if ( ! class_exists( __NAMESPACE__ . '\Google_Sync_Tasks' ) ) {

	class Google_Sync_Tasks {

		const BATCH_SIZE = 400;

		private $sync;

		public function __construct( $sync ) {
			$this->sync = $sync;
		}

		public function init_task () {

			$google_sheets = \BwWinnersGlobalSite\Options::get_option( 'google_sheets' );

			$time = gmdate('Y-m-d H:i:s');

			if ( ! is_array( $google_sheets ) || ! count( $google_sheets ) ) {
				\BwWinnersGlobalSite\Options::set_option( 'google_sheets', [] );

				$task = [
					'status'       => 'complete',
					'started_at'   => $time,
					'completed_at' => $time,
					'errors'      => [],
				];
			} else {
				$task = [
					'status'        => 'running',
					'started_at'    => $time,
					'google_sheets' => $google_sheets,
					'sheet_index'   => 0,
					'offset'        => 0,
					'batch_size'    => self::BATCH_SIZE,
					'errors'        => [],
				];
			}

			return $task;
		}

		public function sync_task ( $task ) {

			$result = $this->sync->sync_batch(
				$task['google_sheets'][$task['sheet_index']],
				$task['offset'],
				$task['batch_size']
			);

			if ( $result['done'] ) {

				if ( $task['sheet_index'] < count( $task['google_sheets'] ) - 1 ) {
					$task['sheet_index']++;
					$task['offset'] = 0;
					return $task;
				} else {
					$task['status'] = 'cleanup';
					return $task;
				}
			}

			$task['offset'] += $result['count'];

			return $task;
		}

		public function clean_task ( $task ) {
			$this->sync->cleanup( $task['started_at'] );

			$task = [
				'status'       => 'complete',
				'started_at'   => $task['started_at'],
				'completed_at' => gmdate('Y-m-d H:i:s'),
				'errors'       => $task['errors'],
			];

			return $task;
		}

		public function fail_task ( $task, string $error ) {

			if ( isset( $task['google_sheets']) && isset( $task['sheet_index'] ) ) {

				if ( isset( $task['google_sheets'][$task['sheet_index']] ) ) {

					$google_sheet = $task['google_sheets'][$task['sheet_index']];

					$task['errors'][$google_sheet]  = $error;

					if ( $task['sheet_index'] < count( $task['google_sheets'] ) - 1 ) {
						$task['sheet_index']++;
						$task['offset'] = 0;
					} else {
						$task['status'] = 'cleanup';
					}

				} else {
					$task = [
						'status' => 'failed',
						'errors' => isset( $task['errors'] ) ? $task['errors'] : []
					];
					$task['errors'] = $error;
				}
			} else {
				$task = [
					'status' => 'failed',
					'errors' => isset( $task['errors'] ) ? $task['errors'] : []
				];
				$task['errors'] = $error;
			}

			return $task;
		}
	}
}
