package downloader

import (
	
	

	

	
)

// RedirectError error is returned when Downloader get CDN redirect.
// See https://core.telegram.org/constructor/upload.fileCdnRedirect.
type RedirectError struct {
	Redirect *tg.UploadFileCDNRedirect
}

// Error implements error interface.
func ( *RedirectError) () string {
	return "redirect to CDN DC " + strconv.Itoa(.Redirect.DCID)
}

// master is a master DC download schema.
// See https://core.telegram.org/api/files#downloading-files.
type master struct {
	client Client

	// precise allows the precise flag for parts that need it, see
	// needPrecise.
	precise  bool
	allowCDN bool
	// retryHandler observes retried transient downloader errors.
	retryHandler RetryHandler
	location     tg.InputFileLocationClass
	// ref is refreshable location, nil if refresh is not set.
	ref *locationRef
}

func ( master) () tg.InputFileLocationClass {
	if .ref != nil {
		return .ref.get()
	}
	return .location
}

// withRefresh calls f with current location, refreshing it on file reference
// errors if refresh is set.
func [ any]( context.Context,  master,  func( tg.InputFileLocationClass) (, error)) (, error) {
	for  := 0; ; ++ {
		 := .currentLocation()
		,  := ()
		if  == nil || .ref == nil || !IsFileReferenceError() {
			return , 
		}
		if  >= maxRefreshAttempts {
			observerFrom().refresh(, refreshLimit, )
			return , 
		}
		.reportRetry(RetryOperationFileReference, +1, )
		,  := .ref.update(, )
		if  != nil {
			 := refreshError
			if errors.Is(, ErrFileNotFound) {
				 = refreshNotFound
			}
			observerFrom().refresh(, , )
			var  
			return , 
		}
		if  {
			// Workers that waited for a refresh of another one don't count.
			observerFrom().refresh(, refreshOK, nil)
		}
	}
}

var _ schema = master{}

func ( master) ( string,  int,  error) {
	if  < 1 ||  == nil || .retryHandler == nil {
		return
	}
	.retryHandler(RetryEvent{
		Operation: ,
		Attempt:   ,
		Err:       ,
	})
}

func ( master) ( context.Context,  int64,  int) (chunk, error) {
	,  := withRefresh(, , func( tg.InputFileLocationClass) (tg.UploadFileClass, error) {
		 := &tg.UploadGetFileRequest{
			Offset:   ,
			Limit:    ,
			Location: ,
		}
		.SetCDNSupported(.allowCDN)
		.SetPrecise(.precise && needPrecise(, ))
		return .client.UploadGetFile(, )
	})
	if  != nil {
		return chunk{}, 
	}

	switch result := .(type) {
	case *tg.UploadFile:
		return chunk{data: .Bytes, tag: .Type}, nil
	case *tg.UploadFileCDNRedirect:
		return chunk{}, &RedirectError{Redirect: }
	default:
		return chunk{}, errors.Errorf("unexpected type %T", )
	}
}

func ( master) ( context.Context,  int64) ([]tg.FileHash, error) {
	return withRefresh(, , func( tg.InputFileLocationClass) ([]tg.FileHash, error) {
		return .client.UploadGetFileHashes(, &tg.UploadGetFileHashesRequest{
			Location: ,
			Offset:   ,
		})
	})
}

const (
	// partAlign is the alignment of offset and limit of upload.getFile
	// without the precise flag.
	partAlign = 4 * 1024
	// partWindow is the window a part must stay within without the precise
	// flag.
	partWindow = 1024 * 1024
)

// needPrecise reports whether a part needs the precise flag of upload.getFile:
// without it, offset and limit must be divisible by 4 KiB, 1 MiB must be
// divisible by limit, and the part must not cross a 1 MiB boundary.
//
// Telegram Desktop and TDLib never set precise, as their parts are aligned;
// gotd's default parts are too, so the flag is only sent for unaligned
// parts, e.g. a resume from an arbitrary offset.
//
// See https://core.telegram.org/api/files#downloading-files.
func ( int64,  int) bool {
	if  <= 0 {
		return true
	}
	 := int64()
	return %partAlign != 0 ||
		%partAlign != 0 ||
		partWindow% != 0 ||
		/partWindow != (+-1)/partWindow
}