<?php

namespace FiloBlu\ActiveCampaign\Observer;

use Exception;
use FiloBlu\ActiveCampaign\Api\Data\JobsInterface;
use FiloBlu\ActiveCampaign\Api\Data\JobsInterfaceFactory;
use FiloBlu\ActiveCampaign\Api\JobsRepositoryInterface;
use FiloBlu\ActiveCampaign\Helper\Data;
use FiloBlu\ActiveCampaign\Model\Config\Source\DirectionType;
use FiloBlu\ActiveCampaign\Model\Config\Source\EntityType;
use FiloBlu\ActiveCampaign\Model\Config\Source\JobStatus;
use FiloBlu\ActiveCampaign\Model\Config\Source\Type;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Psr\Log\LoggerInterface;

/**
 * Class AbstractObserver
 * @package FiloBlu\ActiveCampaign\Observer
 */
abstract class AbstractObserver implements ObserverInterface
{
    /**
     * @var LoggerInterface
     */
    protected $logger;
    /**
     * @var JobsRepositoryInterface
     */
    protected $jobsRepository;
    /**
     * @var Data
     */
    protected $helperData;
    /**
     * @var JobsInterfaceFactory
     */
    protected $jobsFactory;

    /**
     * AbstractObserver constructor.
     * @param LoggerInterface $logger
     * @param JobsRepositoryInterface $jobsRepository
     * @param JobsInterfaceFactory $jobsFactory
     * @param Data $helperData
     */
    public function __construct(
        LoggerInterface $logger,
        JobsRepositoryInterface $jobsRepository,
        JobsInterfaceFactory $jobsFactory,
        Data $helperData
    ) {

        $this->logger = $logger;
        $this->jobsRepository = $jobsRepository;
        $this->helperData = $helperData;
        $this->jobsFactory = $jobsFactory;
    }

    /**
     * @param Observer $observer
     * @return void
     * @throws Exception
     */
    public function execute(Observer $observer)
    {
        $entityId = $observer->getData($this->entity)->getId();

        // IF MODULE IS ENABLED
        if(!$this->helperData->isEnabled()){
            return;
        }
        // IF OBSERVER IS ENABLED
        if (!$this->helperData->isObserverEnabled()) {
            return;
        }
        // SUBSCRIBER CHANGE
        if (!$this->helperData->isSubscriptionChangeObserverEnabled()) {
            return;
        }
        $this->writeJob($entityId);
    }

    /**
     * @param $entityId
     */
    public function writeJob($entityId) {
        try {
            $job = $this->jobsFactory->create();
            $job->setEntity($this->entity)
                ->setEntityId($entityId)
                ->setDirection(DirectionType::DIRECTION_EXPORT)
                ->setType(Type::TYPE_REST)
                ->setStatus(JobStatus::JOB_STATUS_WAITING);
            $this->jobsRepository->save($job);
        } catch (Exception $e) {
            $this->logger->error($e->getMessage());
        }
    }
}
