/*
 * Copyright (c) 2021-present Fabien Potencier <fabien@symfony.com>
 *
 * This file is part of Symfony CLI project
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */

package humanlog

import (
	"regexp"
	"strings"
	"time"

	"github.com/pkg/errors"
)

// Wed Aug 12 16:39:56 2020 (310): [Debug] ...
var phpLogLineRegexp = regexp.MustCompile(`^(.+?) \((?:\d+)\)\: \[(.+?)\] (.+)\s*$`)

func convertPHPLog(in []byte) (*line, error) {
	allMatches := phpLogLineRegexp.FindAllSubmatch(in, -1)
	if allMatches == nil {
		return nil, nil
	}
	line := &line{
		source:  "PHP",
		level:   strings.ToLower(string(allMatches[0][2])),
		message: string(allMatches[0][3]),
		fields:  make(map[string]string),
	}
	// convert date (Wed Aug 12 16:39:56 2020)
	var err error
	m := string(allMatches[0][1])
	line.time, err = time.Parse(`Mon Jan 2 15:04:05 2006`, m)
	if err != nil {
		return nil, errors.WithStack(err)
	}
	return line, nil
}
