package downloader

import (
	
	

	
)

// Verify checks local file data (e.g. a partially downloaded .part file)
// against file hashes from the server (upload.getFileHashes) and returns the
// length of the longest verified prefix.
//
// The r must contain the first size bytes of the file. A trailing part
// shorter than a hash window can be verified only if it is the end of the
// file, otherwise it is not counted.
//
// If the result equals the file size (e.g. Document.Size), the local file is
// complete: do not resume. Otherwise the result ends at a hash window border,
// which is 4KB-aligned, and can be passed to WithOffset to resume a download
// safely together with WithVerify(true). Without verification, WithOffset
// requires the offset to be divisible by the part size, so round the result
// down to it:
//
//	off -= off % partSize
func ( *Builder) ( context.Context,  io.ReaderAt,  int64) ( int64,  error) {
	if  <= 0 {
		return 0, nil
	}
	if  := .downloader.obs;  != nil {
		 = .with()
		defer func() { .verified(, , , ) }()
	}

	 := newVerifier(.schema, .hashes...)
	var  []byte
	for {
		, ,  := .next()
		if  != nil {
			return , errors.Wrap(, "get hashes")
		}
		if ! || .Offset !=  || .Offset >=  {
			// No more hashes, unexpected gap, or end of local data.
			return , nil
		}

		 := int64(.Limit)
		if .Offset+ >  {
			 =  - .Offset
		}
		if int64(cap()) <  {
			 = make([]byte, )
		}
		 := [:]
		if ,  := .ReadAt(, .Offset);  != nil && !errors.Is(, io.EOF) {
			return , errors.Wrap(, "read")
		}
		if !.verify(, ) {
			// Mismatch, or partial window that is not the end of the file.
			return , nil
		}

		 = .Offset + 
		if  < int64(.Limit) ||  >=  {
			// Last (short) window of the file, or all local data is
			// verified: do not ask for hashes past it, Telegram answers
			// VOLUME_LOC_NOT_FOUND at the end of the file.
			return , nil
		}
	}
}