package config

import (
	"io/ioutil"
	"log"

	"gopkg.in/yaml.v3"

	"be.ems/lib/global"
)

type Uri2Object struct {
	Uri    string   `yaml:"uri"`
	Object []Object `yaml:"object"`
}

type Object struct {
	Name   string `yaml:"name"`
	Syntax string `yaml:"syntax"`
	Oid    string `yaml:"oid"`
}

var uri2Object []Uri2Object

func ReadMap(pfile string) (ret error) {
	file, err := ioutil.ReadFile(pfile)
	if err != nil {
		log.Println(err)
		return err
	}

	err = yaml.Unmarshal(file, &uri2Object)
	if err != nil {
		log.Println(err)
		return err
	}
	/*
		for _, v := range uri2Object {
			log.Println(v)
		}
	*/
	return nil
}

func GetOid(uri string, oids *[]string) *[]string {
	for _, v := range uri2Object {
		if uri == v.Uri {
			for _, o := range v.Object {
				*oids = append(*oids, o.Oid)
			}
		}
	}

	return oids
}

func GetOidByFileds(uri string, fields []string, oids *[]string) *[]string {
	for _, v := range uri2Object {
		if uri == v.Uri {
			for _, o := range v.Object {
				if global.IsContain(o.Name, fields) || len(fields) == 0 {
					*oids = append(*oids, o.Oid)
				}
			}
		}
	}

	return oids
}

type NameOid struct {
	Name string
	Oid  string
}

type NameValue struct {
	Name  string
	Value string
}

func GetDataOid(Uri string, nameOids *[]NameOid) *[]NameOid {
	var nameOid NameOid
	for _, v := range uri2Object {
		if Uri == v.Uri {
			for _, o := range v.Object {
				nameOid.Name = o.Name
				nameOid.Oid = o.Oid
				*nameOids = append(*nameOids, nameOid)
			}
		}
	}

	return nameOids
}

func GetDataOidByFields(uri string, fields []string, nameOids *[]NameOid) *[]NameOid {
	var nameOid NameOid
	for _, v := range uri2Object {
		if uri == v.Uri {
			for _, o := range v.Object {
				nameOid.Name = o.Name
				nameOid.Oid = o.Oid
				if len(fields) == 0 || global.IsContainP(nameOid.Name, &fields, len(fields)) {
					*nameOids = append(*nameOids, nameOid)
				}
			}
		}
	}

	return nameOids
}
