package main

import (
	"fmt"
)

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

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

	defer ioctx.Destroy()

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

func RBDFacroty(ioctx IOContexter, rbdname string) (RBD, error) {
	defer func() {
		if v := recover(); v != nil {
			fmt.Println("Shit happened in RBDFactory")
		}
	}()

	image := ioctx.GetImage(rbdname)
	err := image.Open()
	if err != nil {
		panic(err)
	}
	
	defer image.Close()


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

	return RBD{
		Name: rbdname,
		ImageInfo: *info,
	},nil
}
