<?php
namespace SabaiApps\Directories\Component\DirectoryPro\SystemTool;

use SabaiApps\Directories\Component\System\Tool\AbstractImportJsonTool;
use SabaiApps\Directories\Context;
use SabaiApps\Directories\Exception\RuntimeException;
use SabaiApps\Directories\Component\Display\Model\Display;

class ImportDisplaySystemTool extends AbstractImportJsonTool {

	protected function _systemToolInfo() {
		return array(
			'hidden' => true,
		);
	}

	protected function _import( array $data, array &$logs, ?Context $context = null ) {
		if ( empty( $data['entity_type'] )
			|| $data['entity_type'] !== $context->bundle->entitytype_name
			|| empty( $data['bundle_type'] )
			|| $data['bundle_type'] !== $context->bundle->type
			|| empty( $data['type'] )
			|| $data['type'] !== $context->display->type
		) {
			throw new RuntimeException( __( 'Imported display data does not match the existing display.', 'directories-pro' ) );
		}

		// Replace CSS class specific to the existing display with the CSS class of the new display
		$data['data']['css'] = str_replace(
			'.' . Display::cssClass( $data['name'], $data['type'] ),
			'.' . Display::cssClass( $context->display->name, $context->display->type ),
			$data['data']['css']
		);

		$display_name = $context->display->name;
		$display_type = $context->display->type;

		// Remove current
		$this->_application->Display_Create_delete( $context->bundle, $context->display );

		// Create new with imported data
		$data['data']['label'] = isset( $context->display->data['label'] ) ? $context->display->data['label'] : null; // keep current label
		$this->_application->Display_Create( $context->bundle, $display_type, $display_name, $data );

		$logs['success'][] = __( 'Display has been successfully imported.', 'directories-pro' );
	}
}
