package downloader

import (
	
	
	

	

	
	
)

// RefreshFunc returns file location with fresh file reference, e.g. by
// fetching the message, story or profile photo that contains the file again.
//
// See https://core.telegram.org/api/file_reference and package fileref.
type RefreshFunc func(ctx context.Context) (tg.InputFileLocationClass, error)

// maxRefreshAttempts limits consecutive refreshes for one request.
const maxRefreshAttempts = 3

// IsFileReferenceError reports whether err means that the file reference
// of the location is expired or invalid, e.g. FILE_REFERENCE_EXPIRED,
// FILE_REFERENCE_INVALID or FILE_REFERENCE_<n>_EXPIRED.
func ( error) bool {
	,  := tgerr.As()
	if ! {
		return false
	}
	return strings.HasPrefix(.Type, "FILE_REFERENCE_")
}

// locationRef is a file location shared by download workers, which can be
// refreshed on file reference errors.
type locationRef struct {
	mux      sync.Mutex
	location tg.InputFileLocationClass
	refresh  RefreshFunc
}

func ( *locationRef) () tg.InputFileLocationClass {
	.mux.Lock()
	defer .mux.Unlock()
	return .location
}

// update refreshes location if it is still the failed one: concurrent
// workers that failed with the same location do one refresh.
//
// Reports whether this call ran the refresh.
func ( *locationRef) ( context.Context,  tg.InputFileLocationClass) (bool, error) {
	.mux.Lock()
	defer .mux.Unlock()
	if .location !=  {
		// Already refreshed by another worker.
		return false, nil
	}

	,  := .refresh()
	if  != nil {
		return true, errors.Wrap(, "refresh file reference")
	}
	if  == nil {
		return true, errors.New("refresh file reference: nil location")
	}
	.location = 
	return true, nil
}

// WithRefresh sets callback to refresh file location on file reference
// errors (FILE_REFERENCE_*), so download continues from the same offset
// instead of failing.
//
// Concurrent workers share one refresh, and a request is retried at most
// three times. Has no effect for web files.
func ( *Builder) ( RefreshFunc) *Builder {
	if ,  := .schema.(master);  &&  != nil {
		.ref = &locationRef{location: .location, refresh: }
		.schema = 
	}
	return 
}