package kz.cafe.db.service;

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

public class MongoOrderService{
   
   public static void racalculteCounters(MOrder mOrder){
      
      
      long lTotalCount = MongoService.ds.find(MOrder.class)
                                        .filter(MOrder.F_UID, mOrder.UID)
                                        .countAll();
      
      
      long lTotalPaid = MongoService.ds.find(MOrder.class)
                                       .filter(MOrder.F_UID, mOrder.UID)
                                       .filter(MOrder.F_STATUS, OrderConstants.STATUS.PAID.ordinal())
                                       .countAll();
      
      
      
      
      Query<MUser> q = MongoService.ds.createQuery(MUser.class).filter(MUser.F_ID, mOrder.UID);
      
      UpdateOperations<MUser> uOps =
               MongoService.ds.createUpdateOperations(MUser.class).set(MUser.F_COUNTER_ORDERS_TOTAL, lTotalCount);
      MongoService.ds.findAndModify(q, uOps);

      
      uOps =   MongoService.ds.createUpdateOperations(MUser.class).set(MUser.F_COUNTER_ORDERS_PAID, lTotalPaid);
      MongoService.ds.findAndModify(q, uOps);
   }
   public static int racalcultePrice(MOrder mOrder){
      //Let's calculate the price
      mOrder.price = 0;
      for(MOrderItem mOrderItem : MongoService.ds.find(MOrderItem.class, MOrderItem.F_OID, mOrder.ID)){
         mOrder.price += mOrderItem.quantity * (MongoService.get(MCourse.class, mOrderItem.MID).price);
      }
      
      Query<MOrder> qOrder = MongoService.ds.createQuery(MOrder.class).filter(MOrder.F_ID, mOrder.ID);
      UpdateOperations<MOrder> uOrder =   MongoService.ds.createUpdateOperations(MOrder.class).set(MOrder.F_PRICE, mOrder.price);
      MongoService.ds.findAndModify(qOrder, uOrder);
      
      return mOrder.price;
   }
   

   
   
   
   
   public static int racalculteOrderItemPrice(MOrderItem mOrderItem){
      mOrderItem.price = mOrderItem.quantity * (MongoService.get(MCourse.class, mOrderItem.MID).price);
      MongoService.ds.save(mOrderItem);
      
      return mOrderItem.price;
   }
   

}
