/*
 * Copyright (c) 2015 Spotify AB
 *
 * 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.spotify.dns;

import com.google.common.base.Function;
import com.google.common.collect.Sets;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collections;
import java.util.List;
import java.util.Set;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * A {@link ChangeNotifier} that resolves and provides records using a {@link DnsSrvResolver}.
 *
 * <p>The records are refreshable when {@link #run()} is called.
 */
class ServiceResolvingChangeNotifier<T> extends AbstractChangeNotifier<T>
    implements ChangeNotifierFactory.RunnableChangeNotifier<T> {

  private static final Logger log = LoggerFactory.getLogger(ServiceResolvingChangeNotifier.class);

  private final DnsSrvResolver resolver;
  private final String fqdn;
  private final Function<LookupResult, T> resultTransformer;

  private volatile Set<T> records = Collections.emptySet();

  private volatile boolean run = true;

  /**
   * Create a {@link ChangeNotifier} that tracks changes from a {@link DnsSrvResolver}.
   *
   * <p>The list of {@link LookupResult}s will be transformed using the provided function
   * and put into a set. The set will then be compared to the previous set and if a
   * change is detected, the notifier will fire.
   *
   * @param resolver            The resolver to use.
   * @param fqdn                The name to lookup SRV records for
   * @param resultTransformer   The transform function
   */
  ServiceResolvingChangeNotifier(final DnsSrvResolver resolver,
                                 final String fqdn,
                                 final Function<LookupResult, T> resultTransformer) {

    this.resolver = checkNotNull(resolver);
    this.fqdn = checkNotNull(fqdn, "fqdn");
    this.resultTransformer = checkNotNull(resultTransformer, "resultTransformer");
  }

  @Override
  protected void closeImplementation() {
    run = false;
  }

  @Override
  public Set<T> current() {
    return Collections.unmodifiableSet(records);
  }

  @Override
  public void run() {
    if (!run) {
      return;
    }

    try {
      List<LookupResult> nodes = resolver.resolve(fqdn);
      Set<T> currentRecords = Sets.newHashSet();
      for (LookupResult node : nodes) {
        currentRecords.add(resultTransformer.apply(node));
      }

      if (!currentRecords.equals(records)) {
        final ChangeNotification<T> changeNotification =
            newChangeNotification(currentRecords, records);
        records = currentRecords;

        fireRecordsUpdated(changeNotification);
      }
    } catch (Exception e) {
      log.error(e.getMessage(), e);
    }
  }
}


@@ -691,20 +691,28 @@
 collect.
+Immutable
 Set
-s
 ;%0A%0Aimpor
@@ -768,38 +768,8 @@
 y;%0A%0A
-import java.util.Collections;%0A
 impo
@@ -1459,28 +1459,23 @@
 s = 
-Collections.emptySet
+ImmutableSet.of
 ();%0A
@@ -2532,44 +2532,15 @@
 urn 
-Collections.unmodifiableSet(
 records
-)
 ;%0A  
@@ -2684,53 +2684,69 @@
 n);%0A
+%0A
       
-Set%3CT%3E currentRecords = Sets.newHashSet
+ImmutableSet.Builder%3CT%3E builder = ImmutableSet.builder
 ();%0A
@@ -2793,30 +2793,23 @@
         
-currentRecords
+builder
 .add(res
@@ -2840,24 +2840,64 @@
 e));%0A      %7D
+%0A      Set%3CT%3E current = builder.build();
 %0A%0A      if (
@@ -2904,23 +2904,16 @@
 !current
-Records
 .equals(
@@ -3022,23 +3022,16 @@
 (current
-Records
 , record
@@ -3059,23 +3059,16 @@
  current
-Records
 ;%0A%0A     

use immutable sets