package com.deere.igreen.machineconnector2;

import com.deere.igreen.machineconnector2.models.Repository_Replicator;
import org.ektorp.CouchDbConnector;
import org.ektorp.CouchDbInstance;

/**
 * This class is responsible to compact after 10 minutes all Databases on the connected system
 * @author Axel Meyer - John Deere ETIC
 */
public class MCcompact implements Runnable {
    private CouchDbInstance m_dbInstance = null;
    private CouchDbConnector m_dbReplicator = null;
    private Repository_Replicator m_repReplicator = null;
    
    /**
     * Constructor to provide the class the reference to the database
     * @param inst Reference to database
     */
    public MCcompact(CouchDbInstance inst) {
        m_dbInstance = inst;
        m_dbReplicator = m_dbInstance.createConnector("_replicator", false);
        m_repReplicator = new Repository_Replicator(m_dbReplicator);
    }
    
    /**
     * This function runs the Thread with the compaction function
     * after 10 Minutes. After it was running once it stops the Thread.
     */
    @Override
    public void run() {
        try {
            //Thread.sleep(10*60*1000); //Default by spec, but properly to long for some http-servers
            Thread.sleep(40000);
            for(String dbname:m_dbInstance.getAllDatabases()) {
                CouchDbConnector dbconnector = m_dbInstance.createConnector(dbname, false);
                dbconnector.compact();
            }
            return;
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
    
    /**
     * This function deletes replicator entries which are in error state
     * This could be properly because of they have been removed from the syncnodes,
     * but it could also because the nodes are currently not reachable
     * 
     * !!!!Attention!!!!
     * Use this function carefully because the error state dose not include that they
     * are not existing any more
     */
    @Deprecated
    private void replicatorGarbage() {
        for(String docName:m_dbReplicator.getAllDocIds()) {
            if(!docName.equals("_design/_replicator")) {
                if(m_repReplicator.get(docName).getReplication_state().equals("error")) {
                    m_dbReplicator.delete(docName, m_dbReplicator.getRevisions(docName).get(0).getRev());
                }
            }
        }
    }
}
