package telegram

import (
	

	
	
	

	

	
)

// ensureRestart restarts the primary connection and waits until it is ready.
// Reason is restartTimeout or restartMigration, for metrics and logs.
func ( *Client) ( context.Context,  string) error {
	.log.Debug(, "Triggering restart", log.String("reason", ))
	.resetReady()

	select {
	case <-.Done():
		return .Err()
	case .restart <- struct{}{}:
		// Counted once sent, not when abandoned on cancel.
		.meters().restarts.Add(, 1, metric.WithAttributes(attribute.String("reason", )))
		.log.Debug(, "Restart initialized")
	}

	select {
	case <-.Done():
		return .Err()
	case <-.ready.Ready():
		.log.Info(, "Restart ensured")
		return nil
	}
}

func ( *Client) ( context.Context,  int,  bin.Encoder,  bin.Decoder) error {
	// Acquire or cancel.
	select {
	case .migration <- struct{}{}:
	case <-.Done():
		return .Err()
	}
	// Release.
	defer func() {
		<-.migration
	}()

	// Check if someone already migrated.
	 := .session.Load()
	if .DC ==  {
		return .invokeConn(, , )
	}

	,  := context.WithTimeout(, .migrationTimeout)
	defer ()
	if  := .migrateToDc(, );  != nil {
		return errors.Wrap(, "migrate to dc")
	}

	// Re-trying request on another connection.
	return .invokeConn(, , )
}

func ( *Client) ( context.Context,  int) error {
	 := .session.Load().DC
	.log.Info(, "Migrating primary connection",
		log.Int("from_dc", ),
		log.Int("dc_id", ),
	)
	.meters().migrations.Add(, 1, dcAttrs())
	.session.Migrate()
	return .ensureRestart(, restartMigration)
}

// MigrateTo forces client to migrate to another DC.
func ( *Client) ( context.Context,  int) error {
	// Acquire or cancel.
	select {
	case .migration <- struct{}{}:
	case <-.Done():
		return .Err()
	}
	// Release.
	defer func() {
		<-.migration
	}()

	return .migrateToDc(, )
}