<?php

namespace WCML\COT;

use Automattic\WooCommerce\Internal\DataStores\Orders\CustomOrdersTableController;
use Automattic\WooCommerce\Internal\DataStores\Orders\DataSynchronizer;
use Automattic\WooCommerce\Internal\DataStores\Orders\OrdersTableDataStore;
use Automattic\WooCommerce\Utilities\OrderUtil;
use WPML\FP\Maybe;
use WPML\FP\Obj;
use function WPML\FP\invoke;

class Helper {


	const WC_ORDERS = 'wc-orders';

	public static function getTableExists() {
		return self::callStaticMethod( DataSynchronizer::class, 'get_table_exists', false );
	}

	public static function getTableName() {
		return self::callStaticMethod( OrdersTableDataStore::class, 'get_orders_table_name', null );
	}

	public static function getMetaTableName() {
		return self::callStaticMethod( OrdersTableDataStore::class, 'get_meta_table_name', null );
	}

	public static function isUsageEnabled() {
		return self::callStaticMethod( CustomOrdersTableController::class, 'custom_orders_table_usage_is_enabled', false );
	}

	public static function isOrder( int $id ) : bool {
		return OrderUtil::is_order( $id );
	}

	private static function callStaticMethod( $wcClass, $method, $default ) {
		return Maybe::fromNullable( self::getFromContainer( $wcClass ) )
			->map( invoke( $method ) )
			->getOrElse( $default );
	}

	private static function getFromContainer( $wcClass ) {
		try {
			$object = \wc_get_container()->get( $wcClass );
		} catch ( \Exception $e ) {
			return null;
		}

		return $object;
	}

	private static function isOrderAdminScreen( $action ) {
		return is_admin()
			&& Obj::prop( 'page', $_GET ) === self::WC_ORDERS
			&& Obj::prop( 'action', $_GET ) === $action;
	}

	public static function isOrderCreateAdminScreen() {
		return self::isOrderAdminScreen( 'new' );
	}

	public static function isOrderListAdminScreen() {
		return self::isOrderAdminScreen( null ) || self::isOrderAdminScreen( '-1' );
	}

	public static function isOrderEditAdminScreen() {
		return self::isOrderAdminScreen( 'edit' ) && isset( $_GET['id'] );
	}

}
