package telegram

import (
	
	
	

	
	
	

	

	
	
)

// downloadClient is a downloader.Client that serves CDN redirects through
// CDN pools of the client.
type downloadClient struct {
	client *Client
	// raw is the invoker for master DC requests; nil means client.API().
	raw *tg.Client
}

func ( downloadClient) () *tg.Client {
	if .raw != nil {
		return .raw
	}
	return .client.API()
}

func ( downloadClient) (
	 context.Context,
	 *tg.UploadGetFileRequest,
) (tg.UploadFileClass, error) {
	,  := .api().UploadGetFile(, )

	return , 
}

func ( downloadClient) (
	 context.Context,
	 *tg.UploadGetFileHashesRequest,
) ([]tg.FileHash, error) {
	,  := .api().UploadGetFileHashes(, )

	return , 
}

func ( downloadClient) (
	 context.Context,
	 *tg.UploadReuploadCDNFileRequest,
) ([]tg.FileHash, error) {
	,  := .api().UploadReuploadCDNFile(, )

	return , 
}

func ( downloadClient) (
	 context.Context,
	 *tg.UploadGetCDNFileHashesRequest,
) ([]tg.FileHash, error) {
	,  := .api().UploadGetCDNFileHashes(, )

	return , 
}

func ( downloadClient) (
	 context.Context,
	 *tg.UploadGetWebFileRequest,
) (*tg.UploadWebFile, error) {
	return .api().UploadGetWebFile(, )
}

func ( downloadClient) ( context.Context,  int,  int64) (downloader.CDN, io.Closer, error) {
	return cdnProvider{client: .client}.CDN(, , )
}

// cdnProvider implements downloader.CDNProvider using CDN pools of the client.
type cdnProvider struct {
	client *Client
}

func ( cdnProvider) ( context.Context,  int,  int64) (downloader.CDN, io.Closer, error) {
	,  := .client.CDN(, , )
	if  != nil {
		return nil, nil, 
	}
	if  == nil {
		return nil, nil, errors.New("telegram CDN pool returned nil invoker")
	}

	// CDN pools are cached on client level; downloader should not close them
	// by itself; lifecycle is controlled by caller via returned closer.
	 := tg.NewClient()

	return , , nil
}

// Downloader returns file downloader configured for current client: CDN
// policy from Options.AllowCDN, metrics from Options.MeterProvider and logs
// from Options.Logger (named "downloader").
//
// Each call returns a new copy, so its With* methods don't affect other
// downloads; instruments are shared and created once.
//
// It has no Scheduler: use Downloader.WithScheduler with
// Client.DownloadScheduler of the DC the downloads go to.
func ( *Client) () *downloader.Downloader {
	if .downloader == nil {
		// Client is not created by NewClient.
		return downloader.NewDownloader().WithAllowCDN(.allowCDN)
	}
	return .downloader.Clone()
}

// newClientDownloader returns the instrumented base Downloader of a client.
func ( bool,  metric.MeterProvider,  log.Logger) *downloader.Downloader {
	 := downloader.NewDownloader().WithAllowCDN()
	if  != nil {
		 = .WithMeterProvider()
	}
	if  != nil &&  != log.Nop {
		 = .WithLogger(log.Named(, "downloader"))
	}
	return 
}

// homeDownloader returns Downloader with Scheduler of the home DC, if
// Options.DownloadScheduler is set.
func ( *Client) () *downloader.Downloader {
	 := .Downloader()
	if .downloadSchedulers == nil || .session == nil {
		return 
	}
	return .WithScheduler(.DownloadScheduler(.session.Load().DC))
}

// DownloadScheduler returns the download Scheduler of given DC, created on
// first use with Options.DownloadScheduler, or nil if it is not set.
//
// Each DC has its own window: a flood wait of one DC doesn't shrink the
// window of another one.
func ( *Client) ( int) *downloader.Scheduler {
	return .downloadSchedulers.get()
}

// downloaderMeterName is the meter of downloader metrics, the same as of
// downloader.Downloader.WithMeterProvider.
const downloaderMeterName = "github.com/gotd/td/telegram/downloader"

// downloadSchedulers lazily creates one download Scheduler per DC.
//
// With a meter, every Scheduler reports gotd.downloader.scheduler.* with
// attribute dc while the client runs.
type downloadSchedulers struct {
	opts  downloader.SchedulerOptions
	meter metric.Meter // nil if no metrics

	mux  sync.Mutex
	m    map[int]*downloader.Scheduler
	regs map[int]metric.Registration
}

func ( *downloader.SchedulerOptions,  metric.MeterProvider) *downloadSchedulers {
	if  == nil {
		return nil
	}
	 := &downloadSchedulers{
		opts: *,
		m:    map[int]*downloader.Scheduler{},
		regs: map[int]metric.Registration{},
	}
	if  != nil {
		.meter = .Meter(downloaderMeterName)
	}
	return 
}

func ( *downloadSchedulers) ( int) *downloader.Scheduler {
	if  == nil {
		return nil
	}
	.mux.Lock()
	defer .mux.Unlock()
	,  := .m[]
	if ! {
		 = downloader.NewScheduler(.opts)
		.m[] = 
	}
	if ,  := .regs[]; ! && .meter != nil {
		if ,  := .Instrument(.meter, attribute.Int("dc", ));  == nil {
			.regs[] = 
		}
	}
	return 
}

// unregister stops reporting metrics of schedulers, e.g. when Run returns.
// Schedulers used again report them again.
func ( *downloadSchedulers) () {
	if  == nil {
		return
	}
	.mux.Lock()
	defer .mux.Unlock()
	for ,  := range .regs {
		_ = .Unregister()
		delete(.regs, )
	}
}

// registered returns the number of schedulers reporting metrics.
func ( *downloadSchedulers) () int {
	if  == nil {
		return 0
	}
	.mux.Lock()
	defer .mux.Unlock()
	return len(.regs)
}

// CDNProvider returns downloader.CDNProvider that serves CDN redirects using
// cached CDN pools of the client.
//
// Wrap any downloader.Client with it via downloader.WithCDNProvider to enable
// CDN downloads through it.
func ( *Client) () downloader.CDNProvider {
	return cdnProvider{client: }
}

// Download creates Builder for plain file downloads.
func ( *Client) ( tg.InputFileLocationClass) *downloader.Builder {
	return .homeDownloader().Download(downloadClient{client: }, )
}

// DownloadVia creates Builder for plain file downloads, sending requests to
// master DC through given invoker, e.g. a pool from Client.Pool, Client.DC or
// Client.MediaOnly.
//
// Unlike passing tg.NewClient(invoker) to downloader directly, CDN redirects
// are served through CDN pools of the client (if CDN is allowed). No
// Scheduler is set, as the DC of invoker is unknown: use
// Builder.WithScheduler(c.DownloadScheduler(dc)).
func ( *Client) ( tg.Invoker,  tg.InputFileLocationClass) *downloader.Builder {
	return .Downloader().Download(downloadClient{client: , raw: tg.NewClient()}, )
}

// DownloadWeb creates Builder for web file downloads.
func ( *Client) ( tg.InputWebFileLocationClass) *downloader.Builder {
	return .homeDownloader().Web(downloadClient{client: }, )
}

// DownloadWebVia creates Builder for web file downloads through given invoker.
func ( *Client) ( tg.Invoker,  tg.InputWebFileLocationClass) *downloader.Builder {
	return .Downloader().Web(downloadClient{client: , raw: tg.NewClient()}, )
}