package histutil

import 

// NewHybridStore returns a store that provides a view of all the commands that
// exists in the database, plus a in-memory session history.
func ( DB) (Store, error) {
	if  == nil {
		return NewMemStore(), nil
	}
	,  := NewDBStore()
	if  != nil {
		return NewMemStore(), 
	}
	return hybridStore{, NewMemStore()}, nil
}

type hybridStore struct {
	shared, session Store
}

func ( hybridStore) ( store.Cmd) (int, error) {
	,  := .shared.AddCmd()
	.session.AddCmd(store.Cmd{Text: .Text, Seq: })
	return , 
}

func ( hybridStore) () ([]store.Cmd, error) {
	,  := .shared.AllCmds()
	,  := .session.AllCmds()
	if  == nil {
		 = 
	}
	if len() == 0 {
		return , 
	}
	return append(, ...), 
}

func ( hybridStore) ( string) Cursor {
	return &hybridStoreCursor{
		.shared.Cursor(), .session.Cursor(), false}
}

type hybridStoreCursor struct {
	shared    Cursor
	session   Cursor
	useShared bool
}

func ( *hybridStoreCursor) () {
	if .useShared {
		.shared.Prev()
		return
	}
	.session.Prev()
	if ,  := .session.Get();  == ErrEndOfHistory {
		.useShared = true
		.shared.Prev()
	}
}

func ( *hybridStoreCursor) () {
	if !.useShared {
		.session.Next()
		return
	}
	.shared.Next()
	if ,  := .shared.Get();  == ErrEndOfHistory {
		.useShared = false
		.session.Next()
	}
}

func ( *hybridStoreCursor) () (store.Cmd, error) {
	if .useShared {
		return .shared.Get()
	}
	return .session.Get()
}