<?php

namespace FiloBlu\Flow\Psr\Log;

use DateTime;
use FiloBlu\Flow\Api\LogInterface;
use FiloBlu\Flow\Api\LogInterfaceFactory;
use FiloBlu\Flow\Api\LogRepositoryInterface;
use Monolog\Handler\AbstractProcessingHandler;

/**
 * Class Logger
 * @package FiloBlu\Flow\Psr\Log
 */
class LogHandler extends AbstractProcessingHandler
{

    /**
     * @var LogRepositoryInterface
     */
    protected $logRepository;

    /**
     * @var LogInterfaceFactory
     */
    protected $logFactory;

    /**
     * Logger constructor.
     * @param LogRepositoryInterface $logRepository
     * @param LogInterfaceFactory $logFactory
     */
    public function __construct(LogRepositoryInterface $logRepository, LogInterfaceFactory $logFactory)
    {
        $this->logRepository = $logRepository;
        $this->logFactory = $logFactory;
        // TODO : check settings
        parent::__construct();
    }

    /**
     * Writes the record down to the log of the implementing handler
     *
     * @param array $record
     * @return void
     */
    protected function write(array $record) : void
    {
        /** @var $log LogInterface */
        $log = $this->logFactory->create();

        if (isset($record['context']['flow_exception'])) {
            $log->setException($record['context']['flow_exception']);
        }

        if (isset($record['context']['exception'])) {
            $log->setException($record['context']['exception']);
        }

        if (isset($record['context']['flow_inboundflow'])) {
            $log->setMetaFile($record['context']['flow_inboundflow']);
        }

        /** @var $time DateTime */
        $time = $record['datetime'];
        $log->setMessage($record['message']);
        $log->setSeverity(strtolower($record['level_name']));
        $log->setMetaInsertTime($time->format(DATE_ATOM));
        $this->logRepository->save($log);
    }
}
