package req

import (
	
	
	
	

	
	
)

// cchal is a cached challenge and the number of times it's been used.
type cchal struct {
	c *digest.Challenge
	n int
}

type digestAuth struct {
	Username   string
	Password   string
	HttpClient *http.Client
	cache      map[string]*cchal
	cacheMu    sync.Mutex
}

func ( *digestAuth) ( *http.Request,  *digest.Challenge,  int) (*digest.Credentials, error) {
	 := digest.Options{
		Method:   .Method,
		URI:      .URL.RequestURI(),
		GetBody:  .GetBody,
		Count:    ,
		Username: .Username,
		Password: .Password,
	}
	return digest.Digest(, )
}

// challenge returns a cached challenge and count for the provided request
func ( *digestAuth) ( *http.Request) (*digest.Challenge, int, bool) {
	.cacheMu.Lock()
	defer .cacheMu.Unlock()
	 := .URL.Hostname()
	,  := .cache[]
	if ! {
		return nil, 0, false
	}
	.n++
	return .c, .n, true
}

// prepare attempts to find a cached challenge that matches the
// requested domain, and use it to set the Authorization header
func ( *digestAuth) ( *http.Request) error {
	// add cookies
	if .HttpClient.Jar != nil {
		for ,  := range .HttpClient.Jar.Cookies(.URL) {
			.AddCookie()
		}
	}
	// add auth
	, ,  := .challenge()
	if ! {
		return nil
	}
	,  := .digest(, , )
	if  != nil {
		return 
	}
	if  != nil {
		.Header.Set("Authorization", .String())
	}
	return nil
}

func ( *digestAuth) ( http.RoundTripper) HttpRoundTripFunc {
	return func( *http.Request) ( *http.Response,  error) {
		,  := cloner()
		if  != nil {
			return nil, 
		}

		// make a copy of the request
		,  := ()
		if  != nil {
			return nil, 
		}

		// prepare the first request using a cached challenge
		if  := .prepare();  != nil {
			return nil, 
		}

		// the first request will either succeed or return a 401
		,  := .RoundTrip()
		if  != nil || .StatusCode != http.StatusUnauthorized {
			return , 
		}

		// drain and close the first message body
		_, _ = io.Copy(io.Discard, .Body)
		_ = .Body.Close()

		// find and cache the challenge
		 := .URL.Hostname()
		,  := digest.FindChallenge(.Header)
		if  != nil {
			// existing cached challenge didn't work, so remove it
			.cacheMu.Lock()
			delete(.cache, )
			.cacheMu.Unlock()
			if  == digest.ErrNoChallenge {
				return , nil
			}
			return nil, 
		} else {
			// found new challenge, so cache it
			.cacheMu.Lock()
			.cache[] = &cchal{c: }
			.cacheMu.Unlock()
		}

		// make a second copy of the request
		,  := ()
		if  != nil {
			return nil, 
		}

		// prepare the second request based on the new challenge
		if  := .prepare();  != nil {
			return nil, 
		}

		return .RoundTrip()
	}
}

// create response middleware for http digest authentication.
func handleDigestAuthFunc(,  string) ResponseMiddleware {
	return func( *Client,  *Response) error {
		if .Err != nil || .StatusCode != http.StatusUnauthorized {
			return nil
		}
		,  := createDigestAuth(.Request.RawRequest, .Response, , )
		if  != nil {
			return 
		}
		 := .Request
		 := *.RawRequest
		if .Body != nil {
			 = parseRequestBody(, ) // re-setup body
			if  != nil {
				return 
			}
			if .GetBody != nil {
				,  := .GetBody()
				if  != nil {
					return 
				}
				.Body = 
				.GetBody = .GetBody
			}
		}
		if .Header == nil {
			.Header = make(http.Header)
		}
		.Header.Set(header.Authorization, )
		.Response,  = .httpClient.Do(&)
		return 
	}
}

func createDigestAuth( *http.Request,  *http.Response, ,  string) ( string,  error) {
	,  := digest.FindChallenge(.Header)
	if  != nil {
		return "", 
	}
	,  := digest.Digest(, digest.Options{
		Username: ,
		Password: ,
		Method:   .Method,
		URI:      .URL.RequestURI(),
		GetBody:  .GetBody,
		Count:    1,
	})
	if  != nil {
		return "", 
	}
	return .String(), nil
}

// cloner returns a function which makes clones of the provided request
func cloner( *http.Request) (func() (*http.Request, error), error) {
	 := .GetBody
	// if there's no GetBody function set we have to copy the body
	// into memory to use for future clones
	if  == nil {
		if .Body == nil || .Body == http.NoBody {
			 = func() (io.ReadCloser, error) {
				return http.NoBody, nil
			}
		} else {
			,  := io.ReadAll(.Body)
			if  != nil {
				return nil, 
			}
			if  := .Body.Close();  != nil {
				return nil, 
			}
			 = func() (io.ReadCloser, error) {
				return io.NopCloser(bytes.NewReader()), nil
			}
		}
	}
	return func() (*http.Request, error) {
		 := .Clone(.Context())
		,  := ()
		if  != nil {
			return nil, 
		}
		.Body = 
		.GetBody = 
		return , nil
	}, nil
}