<?php
namespace SabaiApps\Directories\Component\Comparison\ViewMode;

use SabaiApps\Directories\Component\Entity\Model\Bundle;
use SabaiApps\Directories\Request;
use SabaiApps\Directories\Component\Field\Type\IComparable;
use SabaiApps\Directories\Component\View\Mode\AbstractMode;

class ComparisonViewMode extends AbstractMode {

	protected function _viewModeInfo() {
		return array(
			'label'             => _x( 'Comparison', 'view mode label', 'directories-pro' ),
			'default_settings'  => array(
				'template'                => 'comparison_compare_entities',
				'compare_image_field'     => '',
				'compare_fields'          => array(),
				'compare_image_width'     => 145,
				'compare_image_size'      => 'medium',
				'compare_max_items'       => 5,
				'compare_label_width'     => 190,
				'compare_item_width'      => 220,
				'compare_highlight_diff'  => true,
				'compare_highlight_color' => '#fff9c4',
				'compare_open_newtab'     => false,
			),
			'features_disabled' => array( 'other' => array( 'add', 'not_found' ) ),
			'mapable'           => false,
			'system'            => true,
		);
	}

	public function viewModeSupports( Bundle $bundle ) {
		return parent::viewModeSupports( $bundle ) && ! empty( $bundle->info['public'] ) && empty( $bundle->info['is_taxonomy'] );
	}

	public function viewModeSettingsForm( Bundle $bundle, array $settings, array $parents = array() ) {
		$comparable_fields = $this->_application->Entity_Field_options(
			$bundle,
			array(
				'interface'       => 'Field\Type\IComparable',
				'return_disabled' => true,
			)
		);
		$image_fields      = $this->_application->Entity_Field_options(
			$bundle,
			array(
				'interface'       => 'Field\Type\IImage',
				'return_disabled' => true,
			)
		);
		return array(
			'compare_image_field'     => array(
				'#type'             => 'select',
				'#title'            => __( 'Image field', 'directories-pro' ),
				'#options'          => array( '' => '— ' . __( 'Select field', 'directories-pro' ) . ' —' ) + $image_fields[0],
				'#options_disabled' => array_keys( $image_fields[1] ),
				'#default_value'    => $settings['compare_image_field'],
				'#horizontal'       => true,
			),
			'compare_image_size'      => array(
				'#type'          => 'select',
				'#title'         => __( 'Image size', 'directories-pro' ),
				'#options'       => array(
					'thumbnail'        => __( 'Thumbnail', 'directories-pro' ),
					'thumbnail_scaled' => __( 'Thumbnail (scaled)', 'directories-pro' ),
					'medium'           => __( 'Medium size', 'directories-pro' ),
					'large'            => __( 'Large size', 'directories-pro' ),
				),
				'#default_value' => $settings['compare_image_size'],
				'#states'        => array(
					'visible' => array(
						$this->_application->Form_Form_fieldName( array( $parents, 'compare_image_field' ), true )  => array(
							'type'  => 'empty',
							'value' => false,
						),
					),
				),
				'#horizontal'    => true,
			),
			'compare_image_width'     => array(
				'#type'          => 'slider',
				'#title'         => __( 'Image width', 'directories-pro' ),
				'#min_value'     => 0,
				'#max_value'     => 300,
				'#field_suffix'  => 'px',
				'#step'          => 5,
				'#integer'       => true,
				'#default_value' => $settings['compare_image_width'],
				'#horizontal'    => true,
				'#states'        => array(
					'visible' => array(
						$this->_application->Form_Form_fieldName( array( $parents, 'compare_image_field' ), true )  => array(
							'type'  => 'empty',
							'value' => false,
						),
					),
				),
			),
			'compare_fields'          => array(
				'#type'             => 'sortablecheckboxes',
				'#title'            => __( 'Fields to compare', 'directories-pro' ),
				'#options'          => $comparable_fields[0],
				'#options_disabled' => array_keys( $comparable_fields[1] ),
				'#default_value'    => $settings['compare_fields'],
				'#horizontal'       => true,
			),
			'compare_max_items'       => array(
				'#type'          => 'slider',
				'#title'         => __( 'Maximum items to compare', 'directories-pro' ),
				'#description'   => __( 'The maximum number of items that can be compared at one time.', 'directories-pro' ),
				'#size'          => 5,
				'#default_value' => $settings['compare_max_items'],
				'#min_value'     => 2,
				'#max_value'     => 20,
				'#step'          => 1,
				'#integer'       => true,
				'#horizontal'    => true,
			),
			'compare_label_width'     => array(
				'#type'          => 'slider',
				'#title'         => __( 'Label column width', 'directories-pro' ),
				'#min_value'     => 100,
				'#max_value'     => 300,
				'#field_suffix'  => 'px',
				'#step'          => 1,
				'#integer'       => true,
				'#default_value' => $settings['compare_label_width'],
				'#horizontal'    => true,
			),
			'compare_item_width'      => array(
				'#type'          => 'slider',
				'#title'         => __( 'Item column width', 'directories-pro' ),
				'#min_value'     => 100,
				'#max_value'     => 400,
				'#field_suffix'  => 'px',
				'#step'          => 5,
				'#integer'       => true,
				'#default_value' => $settings['compare_item_width'],
				'#horizontal'    => true,
			),
			'compare_highlight_diff'  => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Highlight differences', 'directories-pro' ),
				'#default_value' => ! empty( $settings['compare_highlight_diff'] ),
				'#horizontal'    => true,
			),
			'compare_highlight_color' => array(
				'#type'          => 'colorpicker',
				'#title'         => __( 'Highlight color', 'directories-pro' ),
				'#default_value' => $settings['compare_highlight_color'],
				'#states'        => array(
					'visible' => array(
						$this->_application->Form_Form_fieldName( array( $parents, 'compare_highlight_diff' ), true )  => array(
							'type'  => 'checked',
							'value' => true,
						),
					),
				),
				'#horizontal'    => true,
			),
			'compare_open_newtab'     => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Open comparison page in a new tab', 'directories-pro' ),
				'#default_value' => ! empty( $settings['compare_open_newtab'] ),
				'#horizontal'    => true,
			),
		);
	}

	public function viewModeOnInitSettings( Bundle $bundle, array &$viewSettings, Request $request ) {
		if ( ! empty( $viewSettings['view_settings']['compare_image_field'] )
			&& ( ! $field = $this->_application->Entity_Field( $bundle, $viewSettings['view_settings']['compare_image_field'] ) )
		) {
			$viewSettings['view_settings']['compare_image_field'] = '';
		}

		$rows = 1;
		foreach ( $viewSettings['view_settings']['compare_fields'] as $key => $field_name ) {
			if ( ( ! $field = $this->_application->Entity_Field( $bundle, $field_name ) )
				|| ( ! $field_type = $this->_application->Field_Type( $field->getFieldType(), true ) )
				|| ! $field_type instanceof IComparable
				|| ( ! $labels = $field_type->fieldComparableItemLabels( $field ) )
			) {
				unset( $viewSettings['view_settings']['compare_fields'][ $key ] );
				continue;
			}
			$rows += count( $labels );
		}
		$viewSettings['view_settings']['compare_grid_rows'] = $rows;

		if ( ! $entity_ids_str = $request->asStr( 'compare_entity_ids' ) ) {
			return;
		}

		$viewSettings['view_settings']['query']['fields'][ $bundle->entitytype_name . '_id' ] = $entity_ids_str;
		$viewSettings['view_settings']['query']['voting_bookmark_only']                       = false;
		$viewSettings['view_settings']['other']['search']                                     = false;
		$viewSettings['view_settings']['pagination']['no_pagination']                         = true;
		$viewSettings['view_settings']['compare_remove_button']                               = true;

		// Set URL param for pagination and sort links
		$viewSettings['url_params']['compare_entity_ids'] = $entity_ids_str;
	}

	public function viewModeAssets( Bundle $bundle, array $settings ) {
		return array(
			'js_files'  => array(
				'drts-comparison' => array( 'comparison.min.js', array( 'drts' ), 'directories-pro', true ),
			),
			'js'        => array(
				array(
					sprintf(
						'DRTS.Comparison.Grid.getInstance("%s", %s);',
						$bundle->name,
						$this->_application->System_Util_jsonEncode(
							array(
								'emptyListMessage'        => $this->_application->H( __( 'Please select items to compare.', 'directories-pro' ) ),
								'originalPageUrl'         => (string) $this->_application->MainUrl( $bundle->getPath( false ) ),
								'backToOriginalPageLabel' => $this->_application->H( __( 'Back to List', 'directories-pro' ) ),
								'highlightDiff'           => ! empty( $settings['compare_highlight_diff'] ),
								'highlightColor'          => $settings['compare_highlight_color'] ?? null,
							)
						)
					),
				),
			),
			'css_files' => array(
				'drts-comparison' => array( 'comparison.min.css', array( 'drts' ), 'directories-pro' ),
			),
		);
	}
}
