<?php

namespace Smush\Core\Smush;

use Smush\Core\Api\Backoff;

class Smush_Request_WP_Sequential extends Smush_Request {
	/**
	 * @var Backoff
	 */
	private $backoff;
	/**
	 * @var int
	 */
	private $retry_attempts;
	/**
	 * @var int
	 */
	private $retry_wait;

	public function __construct( $options ) {
		$this->backoff        = new Backoff();
		$this->retry_attempts = WP_SMUSH_RETRY_ATTEMPTS;
		$this->retry_wait     = WP_SMUSH_RETRY_WAIT;

		parent::__construct( $options );
	}

	public function do_requests( $file_paths ) {
		$responses = array();
		foreach ( $file_paths as $size_key => $file_path ) {
			$responses[ $size_key ] = $this->do_request( $file_path, $size_key );
		}

		return $responses;
	}

	private function get_api_request_args( $file_path ) {
		return array(
			'headers'    => $this->get_api_request_headers( $file_path ),
			'body'       => $this->get_full_file_contents( $file_path ),
			'timeout'    => $this->get_timeout(),
			'user-agent' => $this->get_user_agent(),
		);
	}

	/**
	 * @param array $request
	 *
	 * @return array|\WP_Error
	 */
	private function make_request_with_backoff( $request ) {
		return $this->backoff->set_wait( $this->retry_wait )
		                     ->set_max_attempts( $this->retry_attempts )
		                     ->enable_jitter()
		                     ->set_decider( array( $this, 'should_retry' ) )
		                     ->run( function () use ( $request ) {
			                     return wp_remote_post( $this->get_url(), $request );
		                     } );
	}

	public function should_retry( $response ) {
		return $this->retry_attempts > 0 && (
				is_wp_error( $response )
				|| 200 !== wp_remote_retrieve_response_code( $response )
			);
	}

	/**
	 * @param $file_path
	 * @param $size_key
	 *
	 * @return mixed
	 */
	public function do_request( $file_path, $size_key ) {
		$request  = $this->get_api_request_args( $file_path );
		$response = $this->make_request_with_backoff( $request );

		do_action( 'smush_http_api_debug', $response, $request );

		return call_user_func( $this->get_on_complete(), $response, $size_key, $file_path );
	}

	/**
	 * @param int $retry_attempts
	 */
	public function set_retry_attempts( $retry_attempts ) {
		$this->retry_attempts = $retry_attempts;
	}

	public function is_supported() {
		return function_exists( 'wp_remote_post' );
	}
}
