<?php

declare (strict_types=1);
namespace VendorInPost\WPDesk\Logger;

use VendorInPost\Monolog\Handler\HandlerInterface;
use VendorInPost\Monolog\Handler\NullHandler;
use VendorInPost\Monolog\Logger;
use VendorInPost\Monolog\Handler\ErrorLogHandler;
use VendorInPost\WPDesk\Logger\WC\WooCommerceHandler;
final class SimpleLoggerFactory implements \VendorInPost\WPDesk\Logger\LoggerFactory
{
    /** @var Settings */
    private $options;
    /** @var string */
    private $channel;
    /** @var Logger */
    private $logger;
    public function __construct(string $channel, \VendorInPost\WPDesk\Logger\Settings $options = null)
    {
        $this->channel = $channel;
        $this->options = $options ?? new \VendorInPost\WPDesk\Logger\Settings();
    }
    public function getLogger($name = null) : \VendorInPost\Monolog\Logger
    {
        if ($this->logger) {
            return $this->logger;
        }
        $logger = new \VendorInPost\Monolog\Logger($this->channel);
        if ($this->options->use_wc_log && \function_exists('wc_get_logger')) {
            $logger->pushHandler(new \VendorInPost\WPDesk\Logger\WC\WooCommerceHandler(\wc_get_logger(), $this->channel));
        }
        // Adding WooCommerce logger may have failed, if so add WP by default.
        if ($this->options->use_wp_log || empty($logger->getHandlers())) {
            $logger->pushHandler($this->get_wp_handler());
        }
        return $this->logger = $logger;
    }
    private function get_wp_handler() : \VendorInPost\Monolog\Handler\HandlerInterface
    {
        if (\defined('VendorInPost\\WP_DEBUG_LOG') && WP_DEBUG_LOG) {
            return new \VendorInPost\Monolog\Handler\ErrorLogHandler(\VendorInPost\Monolog\Handler\ErrorLogHandler::OPERATING_SYSTEM, $this->options->level);
        }
        return new \VendorInPost\Monolog\Handler\NullHandler();
    }
}
