<?php
namespace SabaiApps\Directories\Component\WordPressContent\FieldWidget;

use SabaiApps\Directories\Component\Field;
use SabaiApps\Directories\Component\Entity;

class ImageFieldWidget extends Field\Widget\AbstractWidget {

	protected function _fieldWidgetInfo() {
		return array(
			'label'            => __( 'Image upload field', 'directories-pro' ),
			'field_types'      => array( 'wp_image' ),
			'accept_multiple'  => true,
			'default_settings' => array(
				'non_admin_disable_ajax' => false,
			),
		);
	}

	public function fieldWidgetSettingsForm( $fieldType, Entity\Model\Bundle $bundle, array $settings, array $parents = array(), array $rootParents = array() ) {
		return array(
			'non_admin_disable_ajax' => array(
				'#type'          => 'checkbox',
				'#title'         => __( 'Disable AJAX upload for non-admin users', 'directories-pro' ),
				'#default_value' => ! empty( $settings['non_admin_disable_ajax'] ),
				'#horizontal'    => true,
			),
		);
	}

	public function fieldWidgetForm( Field\IField $field, array $settings, $value = null, ?Entity\Type\IEntity $entity = null, array $parents = array(), $language = null ) {
		$field_settings = $field->getFieldSettings();
		if ( current_user_can( 'upload_files' ) ) {
			$type = 'wp_media_manager';
		} else {
			$type = 'uppy';
			if ( ! empty( $value ) ) {
				foreach ( array_keys( $value ) as $key ) {
					$value[ $key ] = $value[ $key ]['attachment_id'];
				}
			}
		}
		$form = array(
			'#type'              => $type,
			'#max_file_size'     => ! empty( $field_settings['max_file_size'] ) ? $field_settings['max_file_size'] * 1024 : null,
			'#multiple'          => $field->getFieldMaxNumItems() !== 1,
			'#allow_only_images' => true,
			'#default_value'     => $value,
			'#max_num_files'     => $field->getFieldMaxNumItems(),
			'#sortable'          => true,
		);
		if ( ! empty( $settings['non_admin_disable_ajax'] )
			&& ! $this->_application->getUser()->isAdministrator()
		) {
			$form['#type']        = 'file';
			$form['#ajax_upload'] = false;
		}
		if ( $form['#type'] === 'file' ) {
			$form['#upload_dir'] = $this->_application->getComponent( 'System' )->getTmpDir();
		}
		return $form;
	}
}
