// Remote
//
// Douglas
//
// Remote.java

/*  Copyright 2011 Douglas Thrift
 *
 *  This file is part of Big Screen Bot.
 *
 *  Big Screen Bot is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Big Screen Bot is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with Big Screen Bot.  If not, see <http://www.gnu.org/licenses/>.
 */

package net.douglasthrift.bigscreenbot;

import java.io.IOException;

import java.net.InetAddress;
import java.net.UnknownHostException;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;

import java.util.ArrayList;
import java.util.List;

import javax.jmdns.JmDNS;
import javax.jmdns.ServiceInfo;

import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;

import com.google.anymote.common.AnymoteFactory;
import com.google.anymote.common.ErrorListener;

import com.google.anymote.device.DeviceAdapter;
import com.google.anymote.device.MessageReceiver;

import com.google.polo.ssl.DummySSLSocketFactory;

public class Remote
{
    private static final String TYPE = "_anymote._tcp.local.";
    private Settings settings;
    private JmDNS mdns;

    public Remote(Settings settings) throws UnknownHostException, IOException
    {
        this.settings = settings;

        String interfaze = settings.getProperty("interface");

        if (interfaze != null)
            mdns = JmDNS.create(InetAddress.getByName(interfaze));
        else
            mdns = JmDNS.create();
    }

    public List<String> listDevices()
    {
        List<String> devices = new ArrayList<String>();

        for (ServiceInfo info : mdns.list(TYPE))
            devices.add(info.getName());

        return devices;
    }

    public void beginPairDevice(String device) throws NoSuchAlgorithmException, KeyManagementException
    {
        ServiceInfo info = mdns.getServiceInfo(TYPE, device);
        InetAddress address = info.getInetAddresses()[0];
        int port = info.getPort();

        SSLSocketFactory factory = DummySSLSocketFactory.fromKeyManagers(getKeyManagers());
    }

    @Override
    protected void finalize() throws IOException
    {
        mdns.close();
    }

    private KeyManager[] getKeyManagers() throws NoSuchAlgorithmException
    {
        KeyManagerFactory factory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());

        //factory.init(store, "".toCharArray());

        return factory.getKeyManagers();
    }
}

// vim: expandtab
