/**
   * Interface: GET /yes-api/rest/auth/register
   *
   * <p>
   *
   * <p>Interface to list all attributes required for registration
   *
   * <p>
   *
   * <p>
   *
   * <h3>Headers for operation</h3>
   *
   * <p>
   *
   * <table border="1">
   *     <tr><td>Content-Type</td><td>application/json or application/xml</td></tr>
   *     <tr><td>Accept</td><td>application/json or application/xml</td></tr>
   *     <tr><td>yc</td><td>token uuid (optional)</td></tr>
   * </table>
   *
   * <p>
   *
   * <p>
   *
   * <h3>Parameters for register GET operation</h3>
   *
   * <p>
   *
   * <p>NONE
   *
   * <p>
   *
   * <h3>Output</h3>
   *
   * <p>
   *
   * <table border="1">
   *     <tr><td>JSON example</td><td>
   * <pre><code>
   * {
   *   "phone" : null,
   *   "custom" : [
   *     {
   *       "attrvalueId" : 0,
   *       "val" : null,
   *       "displayVals" : null,
   *       "attributeName" : "Marketing Opt in",
   *       "attributeId" : 11051,
   *       "attributeDisplayNames" : {},
   *       "attributeDisplayChoices" : {},
   *       "customerId" : 0
   *     },
   *     {
   *       "attrvalueId" : 0,
   *       "val" : null,
   *       "displayVals" : null,
   *       "attributeName" : "Customer Type",
   *       "attributeId" : 1611,
   *       "attributeDisplayNames" : {
   *         "uk" : "тип пользователя",
   *         "en" : "Customer Type"
   *       },
   *       "attributeDisplayChoices" : {
   *         "uk" : "B-Покупатель,S-Продавец",
   *         "ru" : "B-Покупатель,S-Продавец",
   *         "en" : "B-Buyer,S-Seller"
   *       },
   *       "customerId" : 0
   *     }
   *   ],
   *   "lastname" : null,
   *   "firstname" : null,
   *   "email" : null
   * }
   * </code></pre>
   *     </td></tr>
   *     <tr><td>XML example</td><td>
   * <pre><code>
   * &lt;register-form&gt;
   *     &lt;custom&gt;
   *         &lt;attribute attribute-id="11051" attrvalue-id="0" customer-id="0"&gt;
   *             &lt;attribute-display-choices/&gt;
   *             &lt;attribute-display-names/&gt;
   *             &lt;attribute-name&gt;Marketing Opt in&lt;/attribute-name&gt;
   *         &lt;/attribute&gt;
   *         &lt;attribute attribute-id="1611" attrvalue-id="0" customer-id="0"&gt;
   *             &lt;attribute-display-choices&gt;
   *                 &lt;entry lang="uk"&gt;B-Покупатель,S-Продавец&lt;/entry&gt;
   *                 &lt;entry lang="en"&gt;B-Buyer,S-Seller&lt;/entry&gt;
   *                 &lt;entry lang="ru"&gt;B-Покупатель,S-Продавец&lt;/entry&gt;
   *             &lt;/attribute-display-choices&gt;
   *             &lt;attribute-display-names&gt;
   *                 &lt;entry lang="uk"&gt;тип пользователя&lt;/entry&gt;
   *                 &lt;entry lang="en"&gt;Customer Type&lt;/entry&gt;
   *             &lt;/attribute-display-names&gt;
   *             &lt;attribute-name&gt;Customer Type&lt;/attribute-name&gt;
   *         &lt;/attribute&gt;
   *     &lt;/custom&gt;
   * &lt;/register-form&gt;
   * </code></pre>
   *     </td></tr>
   * </table>
   *
   * <p>
   *
   * <p>
   *
   * @param request request
   * @param response response
   * @return registration data
   */
  @RequestMapping(
      value = "/register",
      method = RequestMethod.GET,
      produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
  public @ResponseBody RegisterFormRO register(
      final HttpServletRequest request, final HttpServletResponse response) {

    cartMixin.persistShoppingCart(request, response);
    final Shop shop = cartMixin.getCurrentShop();

    final List<AttrValueCustomer> avs = customerServiceFacade.getShopRegistrationAttributes(shop);

    final RegisterFormRO formRO = new RegisterFormRO();
    formRO.setCustom(mappingMixin.map(avs, AttrValueCustomerRO.class, AttrValueCustomer.class));

    return formRO;
  }
  /**
   * Interface: PUT /yes-api/rest/auth/register
   *
   * <p>
   *
   * <p>Register interface that allows to register user. The token for the authenticated cart is
   * returned back as response header and also as a cookie.
   *
   * <p>
   *
   * <p>
   *
   * <h3>Headers for operation</h3>
   *
   * <p>
   *
   * <table border="1">
   *     <tr><td>Content-Type</td><td>application/json or application/xml</td></tr>
   *     <tr><td>Accept</td><td>application/json or application/xml</td></tr>
   *     <tr><td>yc</td><td>token uuid (optional)</td></tr>
   * </table>
   *
   * <p>
   *
   * <p>
   *
   * <h3>Parameters for register PUT operation</h3>
   *
   * <p>
   *
   * <p>
   *
   * <p>
   *
   * <table border="1">
   *     <tr><td>JSON example:</td><td>
   * <pre><code>
   * {
   *    "email" : "*****@*****.**",
   *    "firstname" : "Bob",
   *    "lastname" : "Doe",
   *    "phone" : "123123123123",
   *    "custom" : {
   *        "attr1": "value1",
   *        "attr2": "value2",
   *        ...
   *        "attrN": "valueN"
   *    }
   * }
   * </code></pre>
   *     </td></tr>
   *     <tr><td>XML example:</td><td>
   * <pre><code>
   * &lt;login&gt;
   *    &lt;email&gt;[email protected]&lt;/email&gt;
   *    &lt;firstname&gt;Bob&lt;/firstname&gt;
   *    &lt;lastname&gt;Doe&lt;/lastname&gt;
   *    &lt;phone&gt;123123123123&lt;/phone&gt;
   *    &lt;custom&gt;
   *        &lt;entry key="attr1"&gt;value1&lt;/entry&gt;
   *        &lt;entry key="attr2"&gt;value2&lt;/entry&gt;
   *        ...
   *        &lt;entry key="attrN"&gt;valueN&lt;/entry&gt;
   *    &lt;/custom&gt;
   * &lt;/login&gt;
   * </code></pre>
   *     </td></tr>
   * </table>
   *
   * <p>
   *
   * <p>
   *
   * <h3>Output</h3>
   *
   * <p>
   *
   * <table border="1">
   *     <tr><td>JSON example</td><td>
   * <pre><code>
   * {
   *    "success" : true,
   *    "greeting" : "Bob Doe",
   *    "token" : {
   *        "uuid" : "1db8def2-21e0-44d2-aeb0-56baae761129"
   *    },
   *    "error" : null
   * }
   * </code></pre>
   *     </td></tr>
   *     <tr><td>XML example</td><td>
   * <pre><code>
   * &lt;authentication-result&gt;
   *    &lt;greeting&gt;Bob Doe&lt;/greeting&gt;
   *    &lt;success&gt;true&lt;/success&gt;
   *    &lt;token&gt;
   *       &lt;uuid&gt;1db8def2-21e0-44d2-aeb0-56baae761129&lt;/uuid&gt;
   *    &lt;/token&gt;
   * &lt;/authentication-result&gt;
   * </code></pre>
   *     </td></tr>
   * </table>
   *
   * <p>
   *
   * <p>
   *
   * <h3>Error codes</h3>
   *
   * <p>
   *
   * <table border="1">
   *     <tr><td>EMAIL_FAILED</td><td>email must be more than 6 and less than 256 chars (^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*((\.[A-Za-z]{2,}){1}$)) </td></tr>
   *     <tr><td>FIRSTNAME_FAILED</td><td>must be not blank</td></tr>
   *     <tr><td>LASTNAME_FAILED</td><td>must be not blank</td></tr>
   *     <tr><td>PHONE_FAILED</td><td>phone must be more than 4 and less than 13 chars</td></tr>
   *     <tr><td>[ATTRIBUTE CODE]:FAILED</td><td>
   *         E.g. CUSTOMERTYPE_FAILED denoting that mandatory value was missing (could also happen if regex fails but there is no
   *         validation message specified on the {@link org.yes.cart.domain.entity.Attribute#getValidationFailedMessage()})
   *     </td></tr>
   *     <tr><td>[ATTRIBUTE CODE]:FAILED:[Message]</td><td>
   *         E.g. "CUSTOMERTYPE:FAILED:Please choose either Buyer or Seller (UK)" denoting that regex test failed.
   *         RegEx and Message come from {@link org.yes.cart.domain.entity.Attribute#getRegexp()} and
   *         {@link org.yes.cart.domain.entity.Attribute#getValidationFailedMessage()} respectively
   *     </td></tr>
   *     <tr><td>USER_FAILED</td><td>email must not be already registered</td></tr>
   * </table>
   *
   * @param registerRO register parameters (see examples above)
   * @param request request
   * @param response response
   * @return authentication result
   */
  @RequestMapping(
      value = "/register",
      method = RequestMethod.PUT,
      produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE},
      consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
  public @ResponseBody AuthenticationResultRO register(
      final @RequestBody RegisterRO registerRO,
      final HttpServletRequest request,
      final HttpServletResponse response) {

    if (StringUtils.isBlank(registerRO.getEmail())
        || registerRO.getEmail().length() < 6
        || registerRO.getEmail().length() > 256
        || !EMAIL.matcher(registerRO.getEmail()).matches()) {

      return new AuthenticationResultRO("EMAIL_FAILED");
    }

    if (StringUtils.isBlank(registerRO.getFirstname())) {

      return new AuthenticationResultRO("FIRSTNAME_FAILED");
    }

    if (StringUtils.isBlank(registerRO.getLastname())) {

      return new AuthenticationResultRO("LASTNAME_FAILED");
    }

    if (StringUtils.isBlank(registerRO.getPhone())
        || registerRO.getPhone().length() < 4
        || registerRO.getPhone().length() > 13) {

      return new AuthenticationResultRO("PHONE_FAILED");
    }

    if (customerServiceFacade.isCustomerRegistered(registerRO.getEmail())) {

      return new AuthenticationResultRO("USER_FAILED");
    }

    final ShoppingCart cart = cartMixin.getCurrentCart();
    final Shop shop = cartMixin.getCurrentShop();

    final Map<String, Object> data = new HashMap<String, Object>();
    if (registerRO.getCustom() != null) {

      for (final AttrValueCustomer av : customerServiceFacade.getShopRegistrationAttributes(shop)) {

        final Attribute attr = av.getAttribute();
        final String value = registerRO.getCustom().get(attr.getCode());

        if (attr.isMandatory() && StringUtils.isBlank(value)) {

          return new AuthenticationResultRO(attr.getCode() + ":FAILED");

        } else if (StringUtils.isNotBlank(attr.getRegexp())
            && !Pattern.compile(attr.getRegexp()).matcher(value).matches()) {

          final String regexError =
              new FailoverStringI18NModel(attr.getValidationFailedMessage(), null)
                  .getValue(cart.getCurrentLocale());

          if (StringUtils.isBlank(regexError)) {
            return new AuthenticationResultRO(attr.getCode() + ":FAILED");
          }
          return new AuthenticationResultRO(attr.getCode() + ":FAILED:" + regexError);

        } else {

          data.put(attr.getCode(), value);
        }
      }
    }
    data.put("firstname", registerRO.getFirstname());
    data.put("lastname", registerRO.getLastname());
    data.put("phone", registerRO.getPhone());

    final String password =
        customerServiceFacade.registerCustomer(shop, registerRO.getEmail(), data);

    final LoginRO loginRO = new LoginRO();
    loginRO.setUsername(registerRO.getEmail());
    loginRO.setPassword(password);

    return login(loginRO, request, response);
  }