<?php

namespace App\Services\GoogleMaps\Unit;

/**
 * Class GoogleAddressUnit
 *
 * @package App\Packages\GoogleMaps
 */
class GoogleAddressUnit
{
	public $isValid = true;

	public $city;

	public $countryTitle;

	public $countryCode;

	public $street;

	public $fullAddress;

	public $latitude;

	public $longitude;

	public $postalCode;

	public $streetNumber;

	public $streetTitle;

	public $name;

	public $googlePlaceId;

	/**
	 * GoogleAddressUnit constructor.
	 *
	 * @param array $googleAddressResult
	 */
	public function __construct($googleAddressResult)
	{
		if ($googleAddressResult !== null) {
			$this->decode($googleAddressResult);
		} else {
			$this->isValid = false;
		}
	}

	/**
	 * @param $addressData
	 */
	public function decode($addressData)
	{
		foreach (array_get($addressData, 'address_components') as $component) {

			$componentType = array_get($component, 'types.0');
			$longName = array_get($component, 'long_name');
			$shortName = array_get($component, 'short_name');

			switch ($componentType) {
				case 'locality':
					$this->city = $longName;
					break;

				case 'country':
					$this->countryTitle = $longName;
					$this->countryCode = $shortName;
					break;

				case 'postal_code':
					$this->postalCode = $longName;
					break;

				case 'street_number':
					$this->streetNumber = $longName;
					break;

				case 'route':
					$this->streetTitle = $longName;
					break;
			}
		}

		$this->name = array_get($addressData, 'name');
		$this->fullAddress = array_get($addressData, 'formatted_address');
		$this->latitude = array_get($addressData, 'geometry.location.lat');
		$this->longitude = array_get($addressData, 'geometry.location.lng');

		$this->googlePlaceId = array_get($addressData, 'place_id');
		$this->street = $this->streetTitle . " " . $this->streetNumber;
	}
}
