<?php
/**
 * Copyright © 2016 Filoblu S.r.l. All rights reserved.
 */

namespace FiloBlu\Esb\Observer;

use Exception;
use FiloBlu\Esb\Api\Data\EventInterface;
use FiloBlu\Esb\Framework\Event\EventEmitter;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Customer\Api\Data\CustomerInterface;

/**
 * Observer on Customer Save After
 */
class CustomerSaveAfter implements ObserverInterface
{

    /**
     * @var EventEmitter
     */
    private $eventEmitter;
    /**
     * @var EventInterface
     */
    private $eventToEmit;

    /**
     * OrderSaveAfter constructor.
     * @param EventEmitter $eventEmitter
     * @param EventInterface $eventToEmit
     */
    public function __construct(
        EventEmitter $eventEmitter,
        EventInterface $eventToEmit
    ) {
        $this->eventEmitter = $eventEmitter;
        $this->eventToEmit = $eventToEmit;
    }

    /**
     * @param Observer $observer
     * @return void
     * @throws Exception
     */
    public function execute(Observer $observer)
    {
        /** @var CustomerInterface $customerDataObject */
        $customerDataObject = $observer->getEvent()->getCustomerDataObject();
        /** @var $origCustomerDataObject $customerDataObject */
        $origCustomerDataObject = $observer->getEvent()->getOrigCustomerDataObject();

        $customerDataObject->setData('orig_data',$origCustomerDataObject);

        if ($customerDataObject instanceof CustomerInterface) {
            $this->eventEmitter->emit($this->eventToEmit, $customerDataObject);
        } else {
            throw new \RuntimeException('Expected Object of type Customer');
        }
    }
}
