/*
 * Copyright 2000-2012 JetBrains s.r.o.
 *
 * 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 jetbrains.buildServer.agent.android;

import jetbrains.buildServer.util.CollectionsUtil;
import jetbrains.buildServer.util.filters.Filter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Vladislav.Rassokhin
 */
public class AndroidSDKUtil {

  public static final Pattern ANDROID_SDK_TARGET_FOLDER_NAME_PATTERN = Pattern.compile("android\\-(\\d+)", Pattern.CASE_INSENSITIVE);

  @NotNull
  public static Collection<File> getTargets(@NotNull final String sdkHome) {
    File[] targets = new File(sdkHome, "platforms").listFiles();
    if (targets == null || targets.length == 0) {
      return Collections.emptySet();
    }
    return Arrays.asList(targets);
  }

  @Nullable
  public static File getLatestTarget(@NotNull final String sdkHome) {
    Collection<File> targets = getTargets(sdkHome);
    if (targets.isEmpty()) return null;

    final List<File> list = new ArrayList<File>(CollectionsUtil.filterCollection(targets, new Filter<File>() {
      public boolean accept(@NotNull File file) {
        return file.isDirectory() && ANDROID_SDK_TARGET_FOLDER_NAME_PATTERN.matcher(file.getName()).matches();
      }
    }));
    Collections.sort(list, new Comparator<File>() {
      public int compare(File o1, File o2) {
        return getTargetVersion(o2.getName()) - getTargetVersion(o1.getName());
      }
    });
    return list.iterator().next();
  }

  private static int getTargetVersion(@NotNull final String name) {
    final Matcher matcher = ANDROID_SDK_TARGET_FOLDER_NAME_PATTERN.matcher(name);
    if (matcher.matches()) {
      return Integer.valueOf(matcher.group(1));
    }
    return -1;
  }
}
