/*
 * Copyright 2013 - 2013 Cole Wen
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.maodian.flyingcat.im.template;


import org.maodian.flyingcat.im.Type;
import org.maodian.flyingcat.im.Verb;
import org.maodian.flyingcat.im.entity.Account;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.index.Index;
import org.springframework.data.mongodb.core.query.Order;
import org.springframework.stereotype.Service;

/**
 * @author Cole Wen
 *
 */
@Service
@Domain(Type.PERSON)
public class AccountTemplate extends AbstractTemplate {

  @Operation(Verb.CREATE)
  public void register(Account account) {
    MongoTemplate template = getMongoTemplate();
    template.indexOps(Account.class).ensureIndex(new Index("username", Order.ASCENDING).unique());
    getMongoTemplate().insert(account);
  }
}

@@ -637,16 +637,101 @@
 late;%0A%0A%0A
+import java.lang.invoke.MethodHandles;%0A%0Aimport org.maodian.flyingcat.im.IMException;%0A
 import o
@@ -760,16 +760,59 @@
 m.Type;%0A
+import org.maodian.flyingcat.im.UserError;%0A
 import o
@@ -889,16 +889,127 @@
 ccount;%0A
+import org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;%0Aimport org.springframework.dao.DuplicateKeyException;%0A
 import o
@@ -1340,16 +1340,115 @@
 mplate %7B
+%0A  private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
 %0A%0A  @Ope
@@ -1657,16 +1657,28 @@
 que());%0A
+    try %7B%0A  
     getM
@@ -1709,14 +1709,202 @@
 count);%0A
+    %7D catch (DuplicateKeyException e) %7B%0A      log.warn(%22The username %5B%7B%7D%5D has been occupied%22, account.getUsername());%0A      throw IMException.wrap(e, UserError.DUPLICATED_USERNAME);%0A    %7D%0A
   %7D%0A%7D%0A

throw appropriate error code when register fails