<?php

/**
 * @author          Tassos Marinos <info@tassos.gr>
 * @link            http://www.tassos.gr
 * @copyright       Copyright © 2021 Tassos Marinos All Rights Reserved
 * @license         GNU GPLv3 <http://www.gnu.org/licenses/gpl.html> or later
 */

namespace ACF\Helpers\Fields;

defined('_JEXEC') or die;

use YOOtheme\Builder\Joomla\Fields\Type\FieldsType;
use YOOtheme\Str;

class Map
{
	/**
	 * Returns the YooTheme type.
	 * 
	 * @param   object  $field
	 * @param   object  $source
	 * 
	 * @return  array
	 */
	public static function getYooType($field = [], $source = [])
	{
        $fields = [
			[
				'type' => 'String',
                'name' => 'address',
                'metadata' => [
                    'label' => \JText::_('NR_MARKER_ADDRESS')
                ],
			],
			[
				'type' => 'String',
                'name' => 'coordinates',
                'metadata' => [
                    'label' => \JText::_('NR_MARKER_COORDINATES')
                ],
			],
			[
				'type' => 'String',
                'name' => 'latitude',
                'metadata' => [
                    'label' => \JText::_('NR_MARKER_LATITUDE')
                ],
			],
			[
				'type' => 'String',
                'name' => 'longitude',
                'metadata' => [
                    'label' => \JText::_('NR_MARKER_LONGITUDE')
                ],
			],
			[
				'type' => 'String',
                'name' => 'label',
                'metadata' => [
                    'label' => \JText::_('NR_MARKER_LABEL')
                ],
			],
			[
				'type' => 'String',
                'name' => 'description',
                'metadata' => [
                    'label' => \JText::_('NR_MARKER_DESCRIPTION')
                ],
			],
		];
		$name = Str::camelCase(['Field', $field->name], true);
		$source->objectType($name, compact('fields'));

		return ['listOf' => $name];
	}
	
	public static function getYooTypeSubform($field = [], $source = [])
	{
        $fields = [
			[
				'type' => 'String',
                'name' => 'address',
                'metadata' => [
                    'label' => \JText::_('NR_MARKER_ADDRESS')
                ],
				'extensions' => [
					'call' => __CLASS__ . '::resolveSubformAddress',
				],
			],
			[
				'type' => 'String',
                'name' => 'coordinates',
                'metadata' => [
                    'label' => \JText::_('NR_MARKER_COORDINATES')
                ],
				'extensions' => [
					'call' => __CLASS__ . '::resolveSubformCoordinates',
				],
			],
			[
				'type' => 'String',
                'name' => 'latitude',
                'metadata' => [
                    'label' => \JText::_('NR_MARKER_LATITUDE')
                ],
				'extensions' => [
					'call' => __CLASS__ . '::resolveSubformLatitude',
				],
			],
			[
				'type' => 'String',
                'name' => 'longitude',
                'metadata' => [
                    'label' => \JText::_('NR_MARKER_LONGITUDE')
                ],
				'extensions' => [
					'call' => __CLASS__ . '::resolveSubformLongitude',
				],
			],
			[
				'type' => 'String',
                'name' => 'label',
                'metadata' => [
                    'label' => \JText::_('NR_MARKER_LABEL')
                ],
				'extensions' => [
					'call' => __CLASS__ . '::resolveSubformLabel',
				],
			],
			[
				'type' => 'String',
                'name' => 'description',
                'metadata' => [
                    'label' => \JText::_('NR_MARKER_DESCRIPTION')
                ],
				'extensions' => [
					'call' => __CLASS__ . '::resolveSubformDescription',
				],
			],
		];
		$name = Str::camelCase(['Field', $field->name], true) . 'Subform';
		$source->objectType($name, compact('fields'));

		return $name;
	}

	/**
	 * Transforms the field value to an appropriate value that YooTheme can understand.
	 * 
	 * @return  array
	 */
	public static function yooResolve($item, $args, $ctx, $info)
	{
		$name = str_replace('String', '', strtr($info->fieldName, '_', '-'));

		// Check if it's a subform field
        $subfield = clone \ACF\Helpers\Yoo::getSubfield($args['field_id'], $args['context']);

		// When we have a subform field, the $item is an array of values
		if (!$subfield || !is_array($item))
		{
			if (!isset($item->id) || !($field = FieldsType::getField($name, $item, $args['context'])))
			{
				return;
			}
		}
		else
		{
			// Set rawvalue
			$subfield->rawvalue = isset($item["field{$args['field_id']}"]) ? $item["field{$args['field_id']}"] : '';

			// Use the subform field
			$field = $subfield;
		}

        $value = $field->rawvalue;

        if (!is_string($value))
        {
            return;
        }

		if (!$value = json_decode($value, true))
		{
			return;
		}

		foreach ($value as $key => &$v)
		{
			$v['coordinates'] = $v['latitude'] . ',' . $v['longitude'];
		}

		return $value;
	}

	public static function resolveSubformAddress($item, $args)
	{
		return self::resolveSubformItemValue('address', $item);
	}

	public static function resolveSubformCoordinates($item, $args)
	{
		return self::resolveSubformItemValue('coordinates', $item);
	}

	public static function resolveSubformLatitude($item, $args)
	{
		return self::resolveSubformItemValue('latitude', $item);
	}

	public static function resolveSubformLongitude($item, $args)
	{
		return self::resolveSubformItemValue('longitude', $item);
	}

	public static function resolveSubformLabel($item, $args)
	{
		return self::resolveSubformItemValue('label', $item);
	}

	public static function resolveSubformDescription($item, $args)
	{
		return self::resolveSubformItemValue('description', $item);
	}

	public static function resolveSubformItemValue($key = null, $data = [])
	{
		if (!isset($data['markers']))
		{
			return;
		}

		if (!$data = json_decode($data['markers'], true))
		{
			return;
		}

		// Special case
		if ($key === 'coordinates')
		{
			$values = array_map(function($item) {
				return $item['latitude'] . ',' . $item['longitude'];
			}, $data);
		}
		else
		{
			$values = array_filter(array_column($data, $key));
		}

		if (!$values)
		{
			return;
		}
		
        return implode(', ', $values);
	}
}