1/*
2Copyright 2017 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8    http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package apply
18
19// MapElement contains the recorded, local and remote values for a field
20// of type map
21type MapElement struct {
22	// FieldMetaImpl contains metadata about the field from openapi
23	FieldMetaImpl
24
25	// MapElementData contains the value a field was set to
26	MapElementData
27
28	// Values contains the combined recorded-local-remote value of each item in the map
29	// Values contains the values in mapElement.  Element must contain
30	// a Name matching its key in Values
31	Values map[string]Element
32}
33
34// Merge implements Element.Merge
35func (e MapElement) Merge(v Strategy) (Result, error) {
36	return v.MergeMap(e)
37}
38
39// GetValues implements Element.GetValues
40func (e MapElement) GetValues() map[string]Element {
41	return e.Values
42}
43
44var _ Element = &MapElement{}
45
46// MapElementData contains the recorded, local and remote data for a map or type
47type MapElementData struct {
48	RawElementData
49}
50
51// GetRecordedMap returns the Recorded value as a map
52func (e MapElementData) GetRecordedMap() map[string]interface{} {
53	return mapCast(e.recorded)
54}
55
56// GetLocalMap returns the Local value as a map
57func (e MapElementData) GetLocalMap() map[string]interface{} {
58	return mapCast(e.local)
59}
60
61// GetRemoteMap returns the Remote value as a map
62func (e MapElementData) GetRemoteMap() map[string]interface{} {
63	return mapCast(e.remote)
64}
65
66// mapCast casts i to a map if it is non-nil, otherwise returns nil
67func mapCast(i interface{}) map[string]interface{} {
68	if i == nil {
69		return nil
70	}
71	return i.(map[string]interface{})
72}
73
74// HasConflict returns ConflictError if some elements in map conflict.
75func (e MapElement) HasConflict() error {
76	for _, item := range e.GetValues() {
77		if item, ok := item.(ConflictDetector); ok {
78			if err := item.HasConflict(); err != nil {
79				return err
80			}
81		}
82	}
83	return nil
84}
85
86var _ ConflictDetector = &MapElement{}
87