package optionsparser

import (
	"context"
	"encoding/base64"
	"fmt"
	"net/url"
	"strings"
)

const urlTokenPlain = "plain"

func (p *Parser) preprocessURL(u string) string {
	for _, repl := range p.config.URLReplacements {
		u = repl.Regexp.ReplaceAllString(u, repl.Replacement)
	}

	if len(p.config.BaseURL) == 0 || strings.HasPrefix(u, p.config.BaseURL) {
		return u
	}

	return fmt.Sprintf("%s%s", p.config.BaseURL, u)
}

func (p *Parser) decodeBase64URL(ctx context.Context, parts []string) (string, string, error) {
	var format string

	if len(parts) > 1 && p.config.Base64URLIncludesFilename {
		parts = parts[:len(parts)-1]
	}

	encoded := strings.Join(parts, "")
	urlParts := strings.Split(encoded, ".")

	if len(urlParts[0]) == 0 {
		return "", "", newInvalidURLError(ctx, "Image URL is empty")
	}

	if len(urlParts) > 2 {
		return "", "", newInvalidURLError(ctx, "Multiple formats are specified: %s", encoded)
	}

	if len(urlParts) == 2 && len(urlParts[1]) > 0 {
		format = urlParts[1]
	}

	imageURL, err := base64.RawURLEncoding.DecodeString(strings.TrimRight(urlParts[0], "="))
	if err != nil {
		return "", "", newInvalidURLError(ctx, "Invalid url encoding: %s", encoded)
	}

	return p.preprocessURL(string(imageURL)), format, nil
}

func (p *Parser) decodePlainURL(ctx context.Context, parts []string) (string, string, error) {
	var format string

	encoded := strings.Join(parts, "/")
	urlParts := strings.Split(encoded, "@")

	if len(urlParts[0]) == 0 {
		return "", "", newInvalidURLError(ctx, "Image URL is empty")
	}

	if len(urlParts) > 2 {
		return "", "", newInvalidURLError(ctx, "Multiple formats are specified: %s", encoded)
	}

	if len(urlParts) == 2 && len(urlParts[1]) > 0 {
		format = urlParts[1]
	}

	unescaped, err := url.PathUnescape(urlParts[0])
	if err != nil {
		return "", "", newInvalidURLError(ctx, "Invalid url encoding: %s", encoded)
	}

	return p.preprocessURL(unescaped), format, nil
}

func (p *Parser) DecodeURL(
	ctx context.Context,
	parts []string,
) (string, string, error) {
	if len(parts) == 0 {
		return "", "", newInvalidURLError(ctx, "Image URL is empty")
	}

	if parts[0] == urlTokenPlain && len(parts) > 1 {
		return p.decodePlainURL(ctx, parts[1:])
	}

	return p.decodeBase64URL(ctx, parts)
}
