package kz.cafe.db.service;

import javax.mail.internet.*;
import kz.cafe.db.*;
import kz.cafe.db.model.*;
import kz.cafe.exceptions.*;
import org.apache.commons.logging.*;
import com.mongodb.*;

public class MongoUserService extends MongoService{
   private static Log log = LogFactory.getLog(MongoUserService.class);

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







   public static MUser createEmptyProfile(String sLogin) throws AbstractException{
      try{
         InternetAddress emailAddr = new InternetAddress(sLogin);
         emailAddr.validate();
      }
      catch (AddressException ex){
         throw new MaulformedLoginException(sLogin);
      }
      
      
      MUser mUserProfile = new MUser();
      mUserProfile.login = sLogin;
      mUserProfile.ID = MongoService.getUniqueID(MUser.class);
      save(mUserProfile);

      return mUserProfile;
   }





   public static MUser getUserProfile(int UID) throws UserNotFoundException{
      log.debug(LOG + "getUser() UID=" + UID);

      MUser mUserProfile4 = ds.find(MUser.class, MUser.F_UID, UID).get();

      if(mUserProfile4 == null){
         throw new UserNotFoundException(UID);
      }

      if(log.isDebugEnabled()){
         log.debug(LOG + mUserProfile4.toString());
      }

      return mUserProfile4;
   }


   



   public static MUser getUserProfile(String sLogin) throws LoginNotFoundException{
      log.debug(LOG + "getUser() Login=" + sLogin);
      
      sLogin = sLogin.toLowerCase();

      MUser mUser = ds.find(MUser.class, MUser.F_LOGIN, sLogin).get();
      
      if(mUser == null){
         throw new LoginNotFoundException(sLogin);
      }

      log.debug(LOG + mUser);

      return mUser;
   }

   

   
   
   
   
   public static void save(MUser mUser) throws AbstractException{
      log.debug(LOG + "saveUser() UID=" + mUser.ID);
      
      mUser.login = mUser.login.toLowerCase();

      try{
         ds.save(mUser);
      }
      catch (MongoException.DuplicateKey e){
         if(e.getMessage().toLowerCase().contains("$login")){
            log.debug(LOG + "Login is busy.");
            throw new DuplcateLoginException(mUser.login);
         }
         else{
            throw e;
         }
      }

      log.debug(LOG + "ok, saved.");
   }
}
