package kz.cafe.db.service;

import com.google.code.morphia.query.*;
import kz.cafe.db.*;
import kz.cafe.db.model.*;

public class MongoFeedbackService{
   
   public static void racalculte(int ID){
      MFeedback mFeedback = MongoService.ds.find(MFeedback.class, MFeedback.F_ID, ID).get();
      
      if(mFeedback == null){
         return;
      }
      
      long lTotalCount = 0;
      long lRate = 0;
      
      for(int f = 1; f < 6; f++){
         long lCount = MongoService.ds.find(MFeedback.class)
                                      .filter(MFeedback.F_CID, mFeedback.CID)
                                      .filter(MFeedback.F_RATE, f)
                                      .filter(MFeedback.F_DELETED, false)
                                      .filter(MFeedback.F_PUBLISHED, true)
                                      .countAll();
         
         lTotalCount += lCount;
         lRate += lCount * f;
      }
      
      
      if(lTotalCount > 0){
         lRate = lRate / lTotalCount;  
      }
      
      
      
      Query<MCafe> q = MongoService.ds.createQuery(MCafe.class).filter(MCafe.F_ID, mFeedback.CID);
      UpdateOperations<MCafe> uOps =
               MongoService.ds.createUpdateOperations(MCafe.class).set(MCafe.F_RATE, lRate).set(MCafe.F_UPDATED, System.currentTimeMillis());
      MongoService.ds.findAndModify(q, uOps);
   }

}
