1/*
2 * Copyright (C) 2016 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.printservice.recommendation.plugin.hp;
18
19import android.annotation.NonNull;
20import android.content.Context;
21import android.net.nsd.NsdManager;
22import android.net.nsd.NsdServiceInfo;
23import android.text.TextUtils;
24
25import com.android.printservice.recommendation.PrintServicePlugin;
26
27import java.net.InetAddress;
28import java.util.ArrayList;
29
30public abstract class ServiceRecommendationPlugin implements PrintServicePlugin, ServiceListener.Observer {
31
32    protected static final String PDL_ATTRIBUTE = "pdl";
33
34    protected final Object mLock = new Object();
35    protected PrinterDiscoveryCallback mCallback = null;
36    protected final ServiceListener mListener;
37    protected final NsdManager mNSDManager;
38    protected final VendorInfo mVendorInfo;
39    private final int mVendorStringID;
40
41    protected ServiceRecommendationPlugin(Context context, int vendorStringID, VendorInfo vendorInfo, String[] services) {
42        mNSDManager = (NsdManager)context.getSystemService(Context.NSD_SERVICE);
43        mVendorStringID = vendorStringID;
44        mVendorInfo = vendorInfo;
45        mListener = new ServiceListener(context, this, services);
46    }
47
48    @Override
49    public int getName() {
50        return mVendorStringID;
51    }
52
53    @NonNull
54    @Override
55    public CharSequence getPackageName() {
56        return mVendorInfo.mPackageName;
57    }
58
59    @Override
60    public void start(@NonNull PrinterDiscoveryCallback callback) throws Exception {
61        synchronized (mLock) {
62            mCallback = callback;
63        }
64        mListener.start();
65    }
66
67    @Override
68    public void stop() throws Exception {
69        synchronized (mLock) {
70            mCallback = null;
71        }
72        mListener.stop();
73    }
74
75    @Override
76    public void dataSetChanged() {
77        synchronized (mLock) {
78            if (mCallback != null) mCallback.onChanged(getPrinters());
79        }
80    }
81
82    @Override
83    public boolean matchesCriteria(String vendor, NsdServiceInfo nsdServiceInfo) {
84        return TextUtils.equals(vendor, mVendorInfo.mVendorID);
85    }
86
87    public ArrayList<InetAddress> getPrinters() {
88        return mListener.getPrinters();
89    }
90}
91