<?php

namespace Ignite\Core\Models\Import;

use Dubture\Monolog\Reader\LogReader;
use Ignite\Core\Entities\Import;

class LogFormatter
{
    /**
     * @var Import
     */
    protected $import;

    /**
     * ImportLogFormatter constructor.
     *
     * @param Import $import
     */
    public function __construct(Import $import)
    {
        $this->import = $import;
    }

    /**
     * Format each line of the log file.
     *
     * @return \Illuminate\Support\Collection
     */
    public function format()
    {
        $reader = new LogReader(
            $this->import->getLogPath(),
            '/\[(?P<date>.*)\] (?P<logger>\w+).(?P<level>\w+): (?P<message>[^\[\{]+) (?P<context>[\[\{].*[\]\}]) (?P<extra>[\[\{].*[\]\}])/'
        );

        return collect(iterator_to_array($reader))->filter()->map(function ($log) {
            return [
                'date' => $this->formatDate($log),
                'icon' => $this->formatIcon($log),
                'type' => $this->formatType($log),
                'color' => $this->formatColor($log),
                'message' => $this->formatMessage($log),
                'context' => $this->formatContext($log),
            ];
        });
    }

    /**
     * Format the date.
     *
     * @param  array $log
     * @return mixed
     */
    private function formatDate($log)
    {
        return $log['date']->format('Y-m-d h:i:s');
    }

    /**
     * Format the icon based on the level.
     *
     * @param  array $log
     * @return string
     */
    private function formatIcon($log)
    {
        $level = strtolower($log['level']);

        switch ($level) {
            case 'error':
                return 'exclamation-circle';
            case 'info':
                return 'check';
            default:
                return 'info';
        }
    }

    /**
     * Format the correct color based on the level.
     *
     * @param  array $log
     * @return string
     */
    private function formatColor($log)
    {
        $level = strtolower($log['level']);

        switch ($level) {
            case 'error':
                return 'text-danger';
            case 'info':
                return 'text-green';
            default:
                return 'text-muted';
        }
    }

    /**
     * Format the message type.
     *
     * @param  array $log
     * @return string
     */
    private function formatType($log)
    {
        $type = strtolower($log['level']);

        if ($type === 'info') {
            return 'Success';
        }

        return ucwords($type);
    }

    /**
     * Format the message.
     *
     * @param  array $log
     * @return string
     */
    private function formatMessage($log)
    {
        return $log['message'];
    }

    /**
     * Format the context data.
     *
     * @param  array $log
     * @return string
     */
    private function formatContext($log)
    {
        return $log['context'] ?? '';
    }
}
