<?php

namespace FiloBlu\Storelocator\Block\Plugin\Checkout;

use Closure;
use FiloBlu\Storelocator\Helper\Data;
use Magento\Customer\Model\Session;

class LayoutProcessor
{

	public $helper;
	protected $customerSession;

    /**
     * @param Data $helper
     * @param Session $customerSession
     */
	public function __construct(Data $helper, Session $customerSession)
	{
		$this->helper = $helper;
		$this->customerSession = $customerSession;
	}

	/**
	 * @param $subject
	 * @param Closure $proceed
	 * @param $jsLayout
	 * @return mixed
	 */
	public function aroundProcess($subject, Closure $proceed, $jsLayout)
	{

		$countAddresses = 0;

		if ($this->customerSession->isLoggedIn()) {
			$countAddresses = count($this->customerSession->getCustomer()->getAddresses());
		}

		if ($this->helper->getConfig('carriers/pickupinstore/active')) {

			$pickupinstoreForm = [
				'component'   => 'FiloBlu_Storelocator/js/view/pickup-in-store',
				'sortOrder'   => 0,
				'displayArea' => 'shippingAdditional',
				'config'      => [
					'template' => 'FiloBlu_Storelocator/pickup-in-store'
				],
				'deps'        => [
					'0' => 'checkout.steps.shipping-step.shippingAddress'
				]
			];

			$jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children']['shippingAddress']['children']['pickupinstoreData'] = $pickupinstoreForm;

			$pickupinstoreChooser = [
				'component'   => 'FiloBlu_Storelocator/js/view/pickup-in-store-chooser',
				'sortOrder'   => ($countAddresses > 0 ? 0 : 100),
				'displayArea' => ($countAddresses > 0 ? 'address-list' : 'before-form'),
				'config'      => [
					'template' => 'FiloBlu_Storelocator/pickup-in-store-chooser'
				],
				'deps'        => [
					'0' => 'checkout.steps.shipping-step.shippingAddress'
				]
			];

			$jsLayout['components']['checkout']['children']['steps']['children']['shipping-step']['children']['shippingAddress']['children']['pickupinstoreChoser'] = $pickupinstoreChooser;

		}

		return $proceed($jsLayout);
	}
}
