package apimsg

// ResObject error object
type ResObject struct {
	Status int
	Obj    interface{}
}

var objs map[string]*ResObject

// InitError initial error objs
func InitError() {
	objs = make(map[string]*ResObject)

	objs["InternalError"] = &ResObject{
		Status: 500,
		Obj: map[string]string{
			"message": "Server Internal Error",
		},
	}
	objs["DataFormat"] = &ResObject{
		Status: 400,
		Obj: map[string]string{
			"message": "Data Format Error",
		},
	}
	objs["Forbidden"] = &ResObject{
		Status: 403,
		Obj: map[string]string{
			"message": "Forbidden",
		},
	}
	objs["Success"] = &ResObject{
		Status: 200,
		Obj: map[string]string{
			"message": "Success",
		},
	}
	objs["LoginFirst"] = &ResObject{
		Status: 401,
		Obj: map[string]string{
			"message": "please login first",
		},
	}
	objs["TokenTimeout"] = &ResObject{
		Status: 401,
		Obj: map[string]string{
			"message": "token invaildated",
		},
	}
	objs["NotFound"] = &ResObject{
		Status: 404,
		Obj: map[string]string{
			"message": "Not Found",
		},
	}
}

// GetRes get error obj
func GetRes(name string, msg interface{}) *ResObject {
	if objs == nil {
		InitError()
	}

	obj, ok := objs[name]
	if !ok {
		obj = objs["InternalError"]
	}

	resobj := &ResObject{}
	resobj.Status = obj.Status
	switch msg.(type) {
	case string:
		tmp := make(map[string]string)
		tmp["message"] = msg.(string)
		resobj.Obj = tmp
		break
	case map[string]interface{}:
		resobj.Obj = msg
		break
	default:
		resobj.Obj = obj.Obj
	}
	return resobj
}
