/*
 * poc-runner project
 * Copyright (C) 2024 4ra1n
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU 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 General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package rawhttp

import (
	"net/url"
	"regexp"
	"strings"
)

func encodeParams(input string, body bool) string {
	// 如果 input 已经包含了 % 等编码后的结果 直接返回
	encodedPattern := regexp.MustCompile(`%[0-9A-Fa-f]{2}`)
	if encodedPattern.MatchString(input) {
		return input
	}
	query := &strings.Builder{}
	queryParts := strings.Split(input, andSep)
	for i, part := range queryParts {
		kv := strings.SplitN(part, equalSep, 2)
		if len(kv) == 2 {
			encodedKey := url.QueryEscape(kv[0])
			var encodedValue string
			if body {
				encodedValue = url.QueryEscape(kv[1])
			} else {
				encodedValue = strings.ReplaceAll(url.QueryEscape(kv[1]), plusSep, spaceEncode)
			}
			query.WriteString(encodedKey + equalSep + encodedValue)
		} else if len(kv) == 1 {
			encodedKey := url.QueryEscape(kv[0])
			query.WriteString(encodedKey)
		}
		if i != len(queryParts)-1 {
			query.WriteString(andSep)
		}
	}
	return query.String()
}
