package telegram

import (
	
	

	
	

	
	
	
	
	
)

func ( *Client) ( context.Context) error {
	if .storage == nil {
		return nil
	}

	,  := .storage.Load()
	if errors.Is(, session.ErrNotFound) {
		return nil
	}
	if  != nil {
		return errors.Wrap(, "load")
	}

	// If file does not contain DC ID, so we use DC from options.
	 := .session.Load()
	if .DC == 0 {
		.DC = .DC
	}

	// Restoring persisted auth key.
	var  crypto.AuthKey
	copy(.Value[:], .AuthKey)
	copy(.ID[:], .AuthKeyID)

	if .Value.ID() != .ID {
		return errors.New("corrupted key")
	}

	// Re-initializing connection from persisted state.
	.log.Info("Connection restored from state",
		zap.String("addr", .Addr),
		zap.String("key_id", fmt.Sprintf("%x", .AuthKeyID)),
	)

	.connMux.Lock()
	.session.Store(pool.Session{
		DC:      .DC,
		AuthKey: ,
		Salt:    .Salt,
	})
	.conn = .createPrimaryConn(nil)
	.connMux.Unlock()

	return nil
}

func ( *Client) ( tg.Config,  mtproto.Session) error {
	if .storage == nil {
		return nil
	}

	,  := .storage.Load(.ctx)
	if errors.Is(, session.ErrNotFound) {
		// Initializing new state.
		 = nil
		 = &session.Data{}
	}
	if  != nil {
		return errors.Wrap(, "load")
	}

	// Updating previous data.
	.Config = session.ConfigFromTG()
	.AuthKey = .Key.Value[:]
	.AuthKeyID = .Key.ID[:]
	.DC = .ThisDC
	.Salt = .Salt

	if  := .storage.Save(.ctx, );  != nil {
		return errors.Wrap(, "save")
	}

	.log.Debug("Data saved",
		zap.String("key_id", fmt.Sprintf("%x", .AuthKeyID)),
	)
	return nil
}

func ( *Client) ( tg.Config,  mtproto.Session) error {
	.sessionsMux.Lock()
	.sessions[.ThisDC] = pool.NewSyncSession(pool.Session{
		DC:      .ThisDC,
		Salt:    .Salt,
		AuthKey: .Key,
	})
	.sessionsMux.Unlock()

	 := .session.Load().DC
	// Do not save session for non-primary DC.
	if .ThisDC != 0 &&  != 0 &&  != .ThisDC {
		return nil
	}

	.connMux.Lock()
	.session.Store(pool.Session{
		DC:      .ThisDC,
		Salt:    .Salt,
		AuthKey: .Key,
	})
	.cfg.Store()
	.onReady()
	.connMux.Unlock()

	if  := .saveSession(, );  != nil {
		return errors.Wrap(, "save")
	}

	return nil
}