package rbdfactory

import (
	"fmt"
	"rbd_exporter/logger"
	"rbd_exporter/mytypes"
)

func PoolFactory(cephConn mytypes.CephConnector, poolName string) (mytypes.Pool, error) {
	var rbdlist = []mytypes.IRBD{}

	ioctx, err := cephConn.OpenIOContext(poolName)
	if err != nil {
		return mytypes.Pool{}, fmt.Errorf("couldn't set context for pool %s %w", poolName, err)
	}

	defer ioctx.Destroy()

	imageNames, err := ioctx.GetImageNames()
	if err != nil {
		return mytypes.Pool{}, fmt.Errorf("couldn't get list of rbds %w", err)
	}
	for _, rbdName := range imageNames {
		stat, err := RBDFacroty(ioctx, rbdName)
		if err != nil {
			logger.Logger.Errorf("coundn't get stat from disk %s %w", rbdName, err)
		}
		rbdlist = append(rbdlist, stat)
	}
	return mytypes.Pool{
		Name:    poolName,
		HasRBD: len(imageNames) != 0,
		RBDlist: rbdlist,
	}, nil
}

func RBDFacroty(ioctx mytypes.IOContexter, rbdName string) (mytypes.RBD, error) {
	image := ioctx.GetImage(rbdName)
	err := image.Open()
	if err != nil {
		logger.Logger.Errorf("Couldn't open RBD %s",rbdName)
		// logger.Logger.Errorf("Shit happened in RBDFactory")
	}
	
	defer image.Close()


	info,err := image.Stat() 
	if err != nil {
		return mytypes.RBD{},fmt.Errorf("couldn't get stats for image %s %w",rbdName,err)
	}

	return mytypes.RBD{
		Name: rbdName,
		ImageInfo: *info,
	},nil
}
