package com.deere.igreen.machineconnector2;

import java.net.MalformedURLException;
import java.net.URL;
import org.ektorp.*;
import org.ektorp.http.*;
import org.ektorp.impl.*;

/**
 * This is the main entry class for the Machine Connector Reference Implementation
 * This class provides the information to connect to a CouchDB instance
 * @author Axel Meyer - John Deere ETIC
 */
public class MainMC {
    
    private static String m_iGreenID = "";
    private static URL m_CouchServer = null;
    private static URL m_rootServer = null;
    public static String m_Username = "admin";
    public static String m_Password = "iGreenMC";
    
    private static HttpClient m_HttpClient = null;
    private static CouchDbInstance m_dbInstance = null;

    
    /**
     * Main function to start the Machine Connector Server
     * iGreenID is the ID of this instance (de/customer/node)
     * CouchDB_URL is the URL of the local CouchDB instance (localhost)
     * RootServer_URL is the URL to the next reachable root server
     *                (if this instance is the root "root" is required)
     * @param args iGreenID CouchDB_URL RootServer_URL
     */
    public static void main(String[] args) {
        try {
            m_iGreenID = args[0];
            m_CouchServer = new URL(args[1]);
            m_rootServer = new URL(args[2]);
            // Connects to the specific CouchDB instance
            m_HttpClient = new StdHttpClient.Builder()
                    .url(m_CouchServer)
		.username(m_Username)
		.password(m_Password)
                    .socketTimeout(0)
                    .build();
            /*
            m_HttpClient = new StdHttpClient.Builder()
                    .host(m_CouchServer)
                    .port(5984)
                    .username(m_Username)
                    .password(m_Password)
                    .socketTimeout(0)
                    .build();
            
             */
            m_dbInstance = new StdCouchDbInstance(m_HttpClient);
                        
            // Start the Thread to keep attention on the replication
            Thread myMCcoreThread = new Thread(new MCcore(m_dbInstance, m_iGreenID, m_rootServer));
            myMCcoreThread.start();
            
            // Start the Thread to compact the Database after 10 Minutes
            Thread myMCcompactThread = new Thread(new MCcompact(m_dbInstance));
            myMCcompactThread.start();
        } catch (MalformedURLException ex) {
            ex.printStackTrace();
        }
    }
}
