1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.tv.settings.connectivity;
18
19import java.util.Comparator;
20
21import android.net.wifi.ScanResult;
22
23/**
24 * Comparator that sorts Wifi scan results by signal strength and network name.
25 */
26public class ScanResultComparator implements Comparator<ScanResult> {
27
28    private final String mConnectedSSID;
29    private final WifiSecurity mConnectedSecurity;
30
31    public ScanResultComparator(String connectedSSID, WifiSecurity connectedSecurity) {
32        mConnectedSSID = connectedSSID;
33        mConnectedSecurity = connectedSecurity;
34    }
35
36    public ScanResultComparator() {
37        mConnectedSSID = null;
38        mConnectedSecurity = WifiSecurity.NONE;
39    }
40
41    @Override
42    public int compare(ScanResult result1, ScanResult result2) {
43        if (result1 == null) {
44            if (result2 == null) {
45                return 0;
46            } else {
47                return 1;
48            }
49        } else {
50            if (result2 == null) {
51                return -1;
52            } else {
53                WifiSecurity security1 = WifiSecurity.getSecurity(result1);
54                WifiSecurity security2 = WifiSecurity.getSecurity(result2);
55                if (mConnectedSSID != null) {
56                    if (result1.SSID.equals(mConnectedSSID)
57                            && security1.equals(mConnectedSecurity)) {
58                        return -1;
59                    }
60                    if (result2.SSID.equals(mConnectedSSID)
61                            && security2.equals(mConnectedSecurity)) {
62                        return 1;
63                    }
64                }
65                int levelDiff = result2.level - result1.level;
66                if (levelDiff != 0) {
67                    return levelDiff;
68                }
69                if (result1.SSID.equals(result2.SSID)) {
70                    return security1.compareTo(security2);
71                }
72                return result1.SSID.compareTo(result2.SSID);
73            }
74        }
75    }
76}
77