package sample;
import com.hp.ucmdb.api.UcmdbService;
import com.hp.ucmdb.api.history.*;
import com.hp.ucmdb.api.types.UcmdbId;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
/**
 * Query History Sample
 *
 * This is a sample of querying the history data.
 * In this sample we are querying for removed nodes in the last 24 hours.
 * In addition - we query for all changes in the last 24 hours.
 */
public class QueryHistorySample {
    public static void main(String[] args) throws Exception{
        // Create a connection
        UcmdbService ucmdbService = CreateSDKConnectionSample.createSDKConnection();
        // Get the history service
        HistoryService historyService = ucmdbService.getHistoryService();
        // Get the history query factory
        HistoryQueryFactory factory = historyService.getQueryFactory();
        // Calculating last day date
        int dayOffset = 24 * 60 * 60 * 1000;
        Date lastDay = new Date(System.currentTimeMillis()- dayOffset);
        Date now = new Date();
        // Get all deleted nodes in the last 24 hours
        Collection<UcmdbId> removedCIs = historyService.getRemovedCIs("node", lastDay, now);
        System.out.println("Number Of removed nodes - "+ removedCIs.size());
        System.out.println("====================================");
        // Go over the removed CIs
        for (UcmdbId ci : removedCIs) {
            System.out.println("Removed CI ID: "+ci.getAsString());
        }

        // Create a filter from last day till now
        HistoryFilter historyFilter = factory.createHistoryFilter(lastDay, now);
        // Get all changes from the last 24 hours
        Map<UcmdbId,HistoryChanges> map = historyService.getChanges(historyFilter);
        System.out.println("Number Of changed CIs - "+ map.size());
        System.out.println("====================================");
        // Go over each CI and print its changes
        for (Map.Entry<UcmdbId, HistoryChanges> change : map.entrySet()) {
            System.out.println("\nChanges of CI: "+change.getKey());
            System.out.println("----------------------------------------------------------------");
            // Getting the changes of the CI
            Collection<HistoryChange> changes = change.getValue().getChanges();
            // Print the changes
            for (HistoryChange singleChange : changes) {
                System.out.print("Time: ["+singleChange.getChangeTime().toLocaleString()+"] ");
                System.out.println(" Type: ["+singleChange.getChangeType()+"]");
            }
        }

    }
}