package BingoManager

import (
	"context"
	"errors"

	glbingopb "git.alfi.li/gamelang/protobuf/golang-bingo"
)

type BingoServer struct {
	glbingopb.UnimplementedBingoServiceServer

	BingoManager *BingoManager
}

func NewBingoServer(um *BingoManager) *BingoServer {
	return &BingoServer{BingoManager: um}
}

func (bs BingoServer) CreateBingo(ctx context.Context, bingo *glbingopb.Bingo) (*glbingopb.Bingo, error) {
	err := bs.BingoManager.Create(*bingo)
	if err != nil {
		return &glbingopb.Bingo{}, err
	}
	return bingo, nil
}

func (bs BingoServer) DeleteBingo(ctx context.Context, bingo *glbingopb.Bingo) (*glbingopb.Bingo, error) {
	bs.BingoManager.Remove(bingo.GetName())
	return bingo, nil
}

func (bs BingoServer) GetBingo(ctx context.Context, bingo *glbingopb.Bingo) (*glbingopb.Bingo, error) {
	retBingo := bs.BingoManager.Get(*bingo)
	if bingo.GetName() == retBingo.GetName() {
		return &retBingo, nil
	}

	return &glbingopb.Bingo{}, errors.New("Bingo not found")
}

func (bs BingoServer) ListBingo(bingo *glbingopb.Bingo, stream glbingopb.BingoService_ListBingoServer) error {
	bingos := bs.BingoManager.List()
	for _, bingo := range bingos {
		stream.Send(&bingo)
	}
	return nil
}

func (bs BingoServer) ModifyBingo(ctx context.Context, bingo *glbingopb.Bingo) (*glbingopb.Bingo, error) {

	return &glbingopb.Bingo{}, errors.New("bingo not found or password missmatch")
}
