package net.fina.auditlog.core.repository;

import com.mongodb.*;
import net.fina.auditlog.core.domain.AuditLog;
import org.springframework.stereotype.Repository;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Repository
public class AuditLogLoadMongoRepository implements AuditLogLoadRepository {
    public final static String DB_NAME = "fina_audit_log";
    public final static String COLLECTION_NAME = "SYS_AUDIT_LOG";

    @Override
    public long count() {
        long result = -1;
        MongoClient mongoClient = null;
        try {
            mongoClient = new MongoClient();
            DB db = mongoClient.getDB(DB_NAME);
            DBCollection dbCollection = db.getCollection(COLLECTION_NAME);
            result = dbCollection.count();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } finally {
            if (mongoClient != null) {
                mongoClient.close();
            }
        }
        return result;
    }

    @Override
    public List<AuditLog> fetchPage(int start, int length) {
        List<AuditLog> result = new ArrayList<>();

        MongoClient mongoClient = null;
        try {
            mongoClient = new MongoClient();
            DB db = mongoClient.getDB(DB_NAME);
            DBCollection dbCollection = db.getCollection(COLLECTION_NAME);

            DBCursor dbCursor = dbCollection.find();

            dbCursor.skip(start).limit((length));

            while (dbCursor.hasNext()) {
                DBObject dbObject = dbCursor.next();

                AuditLog auditLog = new AuditLog();
                auditLog.setId((long) dbObject.get("id"));
                auditLog.setActorId(dbObject.get("actorId").toString());
                auditLog.setRelevanceTime((Date) dbObject.get("relevanceTime"));
                auditLog.setEntityId(dbObject.get("entityId").toString());
                auditLog.setEntityName(dbObject.get("entityName").toString());
                auditLog.setEntityProperty(dbObject.get("entityProperty")
                        .toString());
                auditLog.setEntityPropertyNewValue(dbObject.get(
                        "entityPropertyNewValue").toString());
                auditLog.setEntityPropertyOldValue(dbObject.get(
                        "entityPropertyOldValue").toString());
                auditLog.setOperationType((int) dbObject.get("operationType"));

                result.add(auditLog);
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } finally {
            if (mongoClient != null) {
                mongoClient.close();
            }
        }
        return result;
    }
}
