package bootkube

import (
	"os"
	"path/filepath"

	"github.com/openshift/installer/pkg/asset"
	"github.com/openshift/installer/pkg/asset/templates/content"
)

const (
	etcdServingCAConfigMapFileName = "etcd-serving-ca-configmap.yaml.template"
)

var etcdServingCAFiles = []string{etcdServingCAConfigMapFileName}

var _ asset.WritableAsset = (*EtcdServingCAConfigMap)(nil)

// EtcdServingCAConfigMap is an asset for the etcd serving CA
type EtcdServingCAConfigMap struct {
	FileList []*asset.File
}

// Dependencies returns all of the dependencies directly needed by the asset
func (t *EtcdServingCAConfigMap) Dependencies() []asset.Asset {
	return []asset.Asset{}
}

// Name returns the human-friendly name of the asset.
func (t *EtcdServingCAConfigMap) Name() string {
	return "EtcdServingCAConfigMap"
}

// Generate generates the actual files by this asset
func (t *EtcdServingCAConfigMap) Generate(parents asset.Parents) error {
	t.FileList = []*asset.File{}
	for _, fileName := range etcdServingCAFiles {
		data, err := content.GetBootkubeTemplate(fileName)
		if err != nil {
			return err
		}
		t.FileList = append(t.FileList, &asset.File{
			Filename: filepath.Join(content.TemplateDir, fileName),
			Data:     []byte(data),
		})
	}

	return nil
}

// Files returns the files generated by the asset.
func (t *EtcdServingCAConfigMap) Files() []*asset.File {
	return t.FileList
}

// Load returns the asset from disk.
func (t *EtcdServingCAConfigMap) Load(f asset.FileFetcher) (bool, error) {
	t.FileList = []*asset.File{}
	for _, fileName := range etcdServingCAFiles {
		file, err := f.FetchByName(filepath.Join(content.TemplateDir, fileName))
		if err != nil {
			if os.IsNotExist(err) {
				return false, nil
			}
			return false, err
		}
		t.FileList = append(t.FileList, file)
	}

	return true, nil
}
