package kz.cafe.client.rest;

import java.util.*;
import javax.servlet.http.*;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import kz.cafe.client.*;
import kz.cafe.client.rest.wrappers.*;
import kz.cafe.constants.*;
import kz.cafe.db.*;
import kz.cafe.db.model.*;
import kz.cafe.db.service.*;
import kz.cafe.utils.*;


@Path("/feedback")
public class FEFeedback extends FEAbstractService{
   //private static Log log = LogFactory.getLog(FEFeedback.class);

   private static final String LOG = "[JR USER] ";

//   private UserSession4 session = null;





   public FEFeedback(@Context HttpServletRequest hsr){
      super(ServiceRequestModel.buildUpponServlet(hsr), LOG);
   }










   
   //---------------------------------------------------------------------------------------------
   //list
   //---------------------------------------------------------------------------------------------
   @GET
   @Path("/list/{LANG}/{TIME}")
   @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
   @SuppressWarnings({ "unchecked" })
   public JRFeedbackListResponse getFeedbacks(@PathParam("LANG") String sLang,
                                              @PathParam("TIME") long lTime){
      JRFeedbackListResponse response = new JRFeedbackListResponse();
      
      InterfaceConstants.LANGS lang = InterfaceConstants.LANGS.valueOf(sLang);
      
      try{
         for(MFeedback mFeedback : (List<MFeedback>) MongoService.getListFrontEnd(MFeedback.class, lTime)){

            if(response.checkDeleted(mFeedback)){
               JRFeedbackListResponse.JMItem item = response.add();
               item.fillIn(mFeedback);
               
               MUser mUser = getUser(mFeedback.UID);

               item.CID    = mFeedback.CID;
               item.avatar = item.checkIsImageEmpty(mUser.image);
               item.login  = mUser.login;
               item.name   = mUser.name;
               item.rate   = mFeedback.rate;
               item.text   = mFeedback.text.get(lang);
               item.title  = mFeedback.title.get(lang);
            }
         }
      }
      catch(Throwable e){
         response = new JRFeedbackListResponse(e);
      }
      
      updateStatistic(MAbstractStatistics.F_FEEDBACKS);
      super.responseTime(response);
      return response;
   }
   
   
   
   
   
   
   //---------------------------------------------------------------------------------------------
   //add new
   //---------------------------------------------------------------------------------------------
   @GET
   @Path("/new/{SID}/{CID}/{rate}")
   @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
   public JREmptyResponse newFeedbacks(@PathParam("SID")  String SID,
                                       @PathParam("CID")  int CID,
                                       @PathParam("rate") int iRate){
      
      return newFeedbacks(SID, CID, iRate, null, null);
   }
   
   
   @GET
   @Path("/new/{SID}/{CID}/{rate}/{lang}/{text}")
   @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
   public JREmptyResponse newFeedbacks(@PathParam("SID")  String SID,
                                       @PathParam("CID")  int CID,
                                       @PathParam("rate") int iRate,
                                       @PathParam("lang") String sLang,
                                       @PathParam("text") String sText){
      JREmptyResponse response = new JREmptyResponse();
      
      try{
         checkSession(SID);
         
         MCafe mCafe = MongoService.getExceptionable(MCafe.class, CID);
         
         MFeedback mFeedback = new MFeedback();
         mFeedback.ID      = MongoService.getUniqueID(MFeedback.class);
         mFeedback.CID     = mCafe.ID;
         mFeedback.UID     = super.UID;
         mFeedback.ownerID = mCafe.ownerID;

         if(sLang == null){
         }
         else{
            InterfaceConstants.LANGS lang = checkLanguage(sLang);
            mFeedback.text.put(lang, sText);
         }
         
         mFeedback.rate = iRate;
         MongoService.save(mFeedback);
         
         
         MongoFeedbackService.racalculte(CID);
         
         MUser mUser = MongoService.get(MUser.class, UID);
         sendEmail(mUser, mCafe, "", iRate, sText);         
      }
      catch(Throwable e){
         response = new JREmptyResponse(e);
      }
      
      updateStatistic(MAbstractStatistics.F_FEEDBACK_NEW);
      super.responseTime(response);
      return response;
   }
   
   

   
   
   @GET
   @Path("/new/{SID}/{CID}/{rate}/{lang}/{text}/{title}")
   @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
   public JREmptyResponse newFeedbacks(@PathParam("SID")   String SID,
                                       @PathParam("CID")   int CID,
                                       @PathParam("rate")  int iRate,
                                       @PathParam("lang")  String sLang,
                                       @PathParam("text")  String sText,
                                       @PathParam("title") String sTitle){
      JREmptyResponse response = new JREmptyResponse();
      
      try{
         checkSession(SID);
         
         MCafe mCafe = MongoService.getExceptionable(MCafe.class, CID);
         
         MFeedback mFeedback = new MFeedback();
         mFeedback.ID      = MongoService.getUniqueID(MFeedback.class);
         mFeedback.CID     = mCafe.ID;
         mFeedback.UID     = super.UID;
         mFeedback.ownerID = mCafe.ownerID;

         if(sLang == null){
         }
         else{
            InterfaceConstants.LANGS lang = checkLanguage(sLang);
            mFeedback.text.put(lang, sText);
            
            mFeedback.title.put(lang, sTitle);
         }
         
         mFeedback.rate = iRate;
         MongoService.save(mFeedback);
         
         
         MongoFeedbackService.racalculte(CID);
         
         MUser mUser = MongoService.get(MUser.class, UID);
         sendEmail(mUser, mCafe, sTitle, iRate, sText);         
      }
      catch(Throwable e){
         response = new JREmptyResponse(e);
      }
      
      updateStatistic(MAbstractStatistics.F_FEEDBACK_NEW);
      super.responseTime(response);
      return response;
   }
   
   
   
   private static void sendEmail(MUser mUser, MCafe mCafe, String sTitle, int iRate, String sText) throws Exception{
      
      HashMap<String, Object> map = new HashMap<String, Object>();
      map.put("cafe_name",   mCafe.name);
      map.put("user_login",  mUser.login);
      map.put("user_name",   mUser.name);
      map.put("user_phone",  mUser.phone);
      map.put("title", sTitle);
      map.put("rate",  iRate);
      map.put("text",  sText);
      
      
      Mailer.sendMail(ServerConstants.getRobot(),
                      ServerConstants.getEmailAddressSystemAdmin(),
                      "Новый отзыв",
                      VelocityProc.run("new_feedback.vm", map));
      
   }
}

