<?php

namespace FernleafSystems\Wordpress\Services\Utilities\WpOrg\Hashes;

use FernleafSystems\Wordpress\Services\Utilities\HttpRequest;
use FernleafSystems\Wordpress\Services\Utilities\WpOrg\Hashes\HashesRequestVO;

abstract class Base {

	const API_URL = 'https://wphashes.com/api/apto-wphashes/v1/';
	const API_ENDPOINT = '';
	const DEFAULT_HASH_ALGO = 'md5';

	/**
	 * @var string
	 */
	protected $sHash;

	/**
	 * @param HashesRequestVO $oReq
	 * @return string[]|null
	 */
	public function queryHashes( HashesRequestVO $oReq ) {
		if ( empty( $oReq->hash ) ) {
			$oReq->hash = $this->getHashAlgo();
		}
		$sUrl = add_query_arg( array_map( 'strtolower', $oReq->getRawDataAsArray() ), $this->getApiUrl() );
		$sResponse = ( new HttpRequest() )->getContent( $sUrl );
		$aData = empty( $sResponse ) ? null : json_decode( $sResponse, true );
		return is_array( $aData ) ? $aData[ 'hashes' ] : null;
	}

	/**
	 * @return string
	 */
	protected function getApiUrl() {
		return static::API_URL.static::API_ENDPOINT;
	}

	/**
	 * @return string
	 */
	public function getHashAlgo() {
		return empty( $this->sHash ) ? static::DEFAULT_HASH_ALGO : $this->sHash;
	}

	/**
	 * @param string $sHashAlgo
	 * @return $this
	 */
	public function setHashAlgo( $sHashAlgo ) {
		$this->sHash = $sHashAlgo;
		return $this;
	}
}