package kz.cafe.db.logs;


import java.util.*;
import kz.cafe.constants.*;
import kz.cafe.db.logs.model.*;
import org.apache.commons.logging.*;
import org.bson.types.*;
import com.google.code.morphia.*;
import com.mongodb.*;

public class MongoLogService{
   private static Log log = LogFactory.getLog(MongoLogService.class);

   private static final String LOG = "[MONGO LogService] ";


   public static final Datastore ds;


   static{
      try{
         Morphia morphia = new Morphia();
         morphia.map(MLogHeader.class);


         Mongo db = new Mongo(ServerConstants.getMongoURL());
         ds = morphia.createDatastore(db, "system_logs");

         ds.ensureIndexes();

         //ds.delete(ds.find(MLogRecord3.class));
      }
      catch (Exception e){
         throw new Error("Can not connect to Mongo", e);
      }
   }






   public static MLogHeader addHeader(MLogHeader mLogHeader3){
      log.trace(LOG);

      ds.save(mLogHeader3);

      return mLogHeader3;
   }







   public static void addBody(MLogBody mLogBody3){
      log.trace(LOG);

      ds.save(mLogBody3);
   }




   public static List<MLogHeader> getLogHeaders(int iLimit){
      return ds.find(MLogHeader.class).order("-date").limit(iLimit).asList();
   }
   


   public static List<MLogHeader> getUserLogHeaders(long UID){
      return ds.find(MLogHeader.class, "UID", UID).order("date").asList();
   }
   public static List<MLogHeader> getUserLogHeaders(String SID){
      return ds.find(MLogHeader.class, "SID", SID).order("date").asList();
   }


   public static List<MLogHeader> getUserLogHeader(long UID, long date){
      return ds.find(MLogHeader.class, "UID", UID).filter("date", date).asList();
   }






   public static MLogBody getUserRecord(ObjectId header){
      return ds.find(MLogBody.class, "header", header).get();
   }
}
