/*
 * Copyright 2017 Netflix, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License")
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.netflix.spinnaker.orca.pipeline.model;

import java.util.HashMap;
import java.util.Map;
import javax.annotation.Nullable;
import com.google.common.collect.ForwardingMap;
import com.netflix.spectator.api.Id;
import com.netflix.spectator.api.Registry;

class AlertOnAccessMap<E extends Execution<E>> extends ForwardingMap<String, Object> {

  private final Map<String, Object> delegate;
  private final Registry registry;
  private final Id counterId;

  AlertOnAccessMap(Execution<E> execution, Registry registry, Map<String, Object> delegate) {
    this.registry = registry;
    this.delegate = delegate;
    counterId = registry
      .createId("global.context.access")
      .withTag("execution", execution.getId())
      .withTag("application", execution.getApplication())
      .withTag("name", execution.getName());
  }

  AlertOnAccessMap(Execution<E> execution, Registry registry) {
    this(execution, registry, new HashMap<>());
  }

  @Override protected Map<String, Object> delegate() { return delegate; }

  @Override public Object get(@Nullable Object key) {
    registry
      .counter(counterId.withTag("key", String.valueOf(key)))
      .increment();
    return super.get(key);
  }
}

@@ -939,16 +939,56 @@
 ect%3E %7B%0A%0A
+  private final Execution%3CE%3E execution;%0A
   privat
@@ -1060,16 +1060,17 @@
 gistry;%0A
+%0A
   privat
@@ -1075,31 +1075,8 @@
 ate 
-final Id counterId;%0A%0A  
 Aler
@@ -1176,72 +1176,48 @@
 his.
-registry = registry;%0A    this.delegate = delegate;%0A    counterId
+execution = execution;%0A    this.registry
  = r
@@ -1227,198 +1227,38 @@
 stry
+;
 %0A
- 
     
- .createId(%22global.context.access%22)%0A      .withTag(%22execution%22, execution.getId())%0A      .withTag(%22application%22, execution.getApplication())%0A      .withTag(%22name%22, execution.getName())
+this.delegate = delegate
 ;%0A  
@@ -1509,16 +1509,31 @@
 y) %7B%0A   
+ Id counterId =
  registr
@@ -1546,60 +1546,271 @@
   .c
-ounter(counterId.withTag(%22key%22, String.valueOf(key))
+reateId(%22global.context.access%22)%0A      .withTag(%22execution%22, execution.getId())%0A      .withTag(%22application%22, execution.getApplication())%0A      .withTag(%22name%22, execution.getName())%0A      .withTag(%22key%22, String.valueOf(key));%0A    registry%0A      .counter(counterId
 )%0A  

fix NPE caused by late assignment of pipeline id