package main

import (
	"encoding/json"
	"fmt"

	// "github.com/ceph/go-ceph/rados"
	"github.com/ceph/go-ceph/rbd"
	pipe "gopkg.in/pipe.v2"
)

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

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

	defer ioctx.Destroy()

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

func RBDFacroty(poolname string, rbdname string) (RBD, error) {

	rbdPath := fmt.Sprintf("%s/%s", poolname, rbdname)
	args := []string{"du", "--format", "json", rbdPath}

	p := pipe.Line(
		pipe.Exec("rbd", args...),
	)
	output, err := pipe.CombinedOutput(p)
	if err != nil {
		fmt.Errorf("Error in processing RBD %v", err)
	}

	var rbdImage RBDUsage
	if err := json.Unmarshal(output, &rbdImage); err != nil {
		fmt.Errorf("Error in unmarshaling %w", err)
	}
	return RBD{
		Name: rbdImage.Images[0].Name,
		Id: rbdImage.Images[0].Id,
		RequestedSize: rbdImage.Images[0].RequestedSize,
		UsedSize: rbdImage.Images[0].UsedSize,
	}, nil
}