package telegram

import (
	

	
	

	

	
	
	
)

const defaultFilePoolSize = 4

// FileDC returns invoker for file requests (e.g. upload.getFile) to given DC.
//
// Unlike Client.DC, the pool is created once per DC (concurrent callers share
// creation), cached and closed when Run returns, so callers can call FileDC
// for every request. Its size is Options.FilePoolSize.
//
// The invoker:
//   - is wrapped with Options.Middlewares (flood wait, rate limit, metrics);
//   - uses the primary session for the home DC, without authorization
//     transfer;
//   - follows FILE_MIGRATE_X errors to FileDC(X).
//
// Must be called while client is running, otherwise an error is returned.
//
// If a request fails as unauthorized, the cached pool of that DC is dropped
// and the request is retried once on a new pool with authorization transfer.
func ( *Client) ( context.Context,  int) (tg.Invoker, error) {
	.fileInvokersMux.Lock()
	,  := .fileInvokers[]
	.fileInvokersMux.Unlock()
	if  {
		return , nil
	}

	// Create pool eagerly to return creation errors.
	if ,  := .cachedDC(, .filePools, );  != nil {
		return nil, errors.Wrapf(, "create pool to DC %d", )
	}

	 = chainMiddlewares(fileDCInvoker{client: , dc: }, .mw...)
	.fileInvokersMux.Lock()
	if ,  := .fileInvokers[];  {
		 = 
	} else {
		.fileInvokers[] = 
	}
	.fileInvokersMux.Unlock()
	return , nil
}

// fileDCInvoker invokes requests on cached file pool of DC, following
// FILE_MIGRATE errors.
type fileDCInvoker struct {
	client *Client
	dc     int
}

// maxFileMigrations bounds FILE_MIGRATE hops of one request.
const maxFileMigrations = 2

func ( fileDCInvoker) ( context.Context,  bin.Encoder,  bin.Decoder) error {
	 := .dc
	for  := 0; ; ++ {
		 := .client.invokeCachedDC(, .client.filePools, , , )
		,  := tgerr.AsType(, "FILE_MIGRATE")
		if ! ||  >= maxFileMigrations || .Argument ==  {
			return 
		}
		.client.log.Debug(, "Following FILE_MIGRATE",
			log.Int("from_dc", ),
			log.Int("dc_id", .Argument),
			log.Int("hop", +1),
		)
		.client.meters().fileMigrations.Add(, 1, dcAttrs(.Argument,
			attribute.String("source", "file"),
		))
		 = .Argument
	}
}