package repocli

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"net/http"
	"strconv"
	"strings"

	ocidigest "github.com/opencontainers/go-digest"
)

func (cli *Client) GetRawManifest(ctx context.Context, rawrepo string) (bool, string, []byte, error) {
	var err error
	var exist bool
	var mime string
	var man []byte

	fmt.Printf("=== %s\n", rawrepo)
	ref, err := NewReferer(rawrepo)
	if err != nil {
		return exist, mime, man, err
	}
	uri := ref.ManifestEP()

	req, err := http.NewRequestWithContext(ctx, http.MethodGet, uri, nil)
	if err != nil {
		return exist, mime, man, err
	}
	req.Header.Set("User-Agent", cli.userAgent)
	req.Header.Set("Accept", "*/*")
	resp, err := cli.httpClient.Do(req)
	if err != nil {
		return exist, mime, man, err
	}
	defer resp.Body.Close()

	if resp.StatusCode == http.StatusNotFound {
		return exist, mime, man, err
	}
	if resp.StatusCode != http.StatusOK {
		err := fmt.Errorf("Unxected response code %s", resp.Status)
		return exist, mime, man, err
	}
	digstr := resp.Header.Get("Docker-Content-Digest")
	if digstr == "" {
		err := fmt.Errorf("Empty digest declaration")
		return exist, mime, man, err
	}
	contentLength := resp.Header.Get("Content-Length")
	if contentLength == "" {
		err = errors.New("Empty Content-Length header")
		return exist, mime, man, err
	}
	manSize, err := strconv.ParseInt(contentLength, 10, 64)
	if err != nil {
		return exist, mime, man, err
	}
	mime = resp.Header.Get("Content-Type")
	if mime == "" {
		err := fmt.Errorf("Empty MIME type declaration")
		return exist, mime, man, err
	}
	digstr = strings.ToLower(digstr)
	digobj, err := ocidigest.Parse(digstr)
	if err != nil {
		return exist, mime, man, err
	}
	verifier := digobj.Verifier()
	buffer := bytes.NewBuffer(nil)
	mwriter := io.MultiWriter(buffer, verifier)
	recSize, err := Copy(ctx, mwriter, resp.Body)
	if manSize != recSize {
		err := fmt.Errorf("Mismatch declared and actual size")
		return exist, mime, man, err
	}
	man = buffer.Bytes()
	if !verifier.Verified() {
		err := fmt.Errorf("Mismatch digest declaration and actual")
		return exist, mime, man, err
	}
	exist = true
	return exist, mime, man, err
}
