/*
  * Copyright 2026 Oleg Borodin <onborodin@gmail.com>
 *
 *
*/

package auxhttp

import (
	"fmt"
	"strconv"
	"strings"
)

func ParseOCIContentRange(ref string) (int64, int64, error) {
	var start, end int64
	var err error

	startstop := strings.TrimSpace(ref)
	tmp := strings.SplitN(startstop, "-", 2)
	if len(tmp) != 2 {
		err = fmt.Errorf("Wrong Content-Range definition, strange range def %v", startstop)
		return start, end, err
	}
	startstr := tmp[0]
	endstr := tmp[1]

	start, err = strconv.ParseInt(startstr, 10, 64)
	if err != nil {
		err = fmt.Errorf("Wrong Content-Range definition, strange start %s", startstr)
		return start, end, err
	}
	end, err = strconv.ParseInt(endstr, 10, 64)
	if err != nil {
		err = fmt.Errorf("Wrong Content-Range definition, strange end %s", endstr)
		return start, end, err
	}
	return start, end, err
}

func ParseContentRange(ref string) (int64, int64, int64, error) {
	var start, end, total int64
	var err error

	const bytesUnit = "bytes"

	tmp := strings.SplitN(ref, " ", 2)
	if len(tmp) != 2 {
		err := fmt.Errorf("Wrong Content-Range definition, len is only %d", len(tmp))
		return start, end, total, err
	}
	unit := strings.ToLower(tmp[0])
	if unit != bytesUnit {
		err = fmt.Errorf("Wrong Content-Range definition, strange length def %s", unit)
		return start, end, total, err
	}
	ranger := strings.TrimSpace(tmp[1])

	tmp = strings.Split(ranger, "/")
	if len(tmp) != 2 {
		err = fmt.Errorf("Wrong Content-Range definition, dont found total")
		return start, end, total, err
	}
	totalstr := tmp[1]
	if totalstr == "*" {
		total = 0
	} else {
		total, err = strconv.ParseInt(totalstr, 10, 64)
		if err != nil {
			return start, end, total, err
		}
	}
	startstop := tmp[0]
	tmp = strings.SplitN(startstop, "-", 2)
	if len(tmp) != 2 {
		err = fmt.Errorf("Wrong Content-Range definition, strange range def %v", startstop)
		return start, end, total, err
	}
	startstr := tmp[0]
	endstr := tmp[1]

	start, err = strconv.ParseInt(startstr, 10, 64)
	if err != nil {
		err = fmt.Errorf("Wrong Content-Range definition, strange start %s", startstr)
		return start, end, total, err
	}
	end, err = strconv.ParseInt(endstr, 10, 64)
	if err != nil {
		err = fmt.Errorf("Wrong Content-Range definition, strange end %s", endstr)
		return start, end, total, err
	}
	return start, end, total, err
}
