/**
   * Test if the user can create new applications because we limit the number per user
   *
   * @param application
   * @param serverName
   * @throws CheckException
   * @throws ServiceException
   */
  @Override
  public void checkCreate(Application application, String serverName)
      throws CheckException, ServiceException {

    logger.debug("--CHECK APP COUNT--");

    if (this.countApp(application.getUser()) >= Integer.parseInt(numberMaxApplications)) {
      throw new ServiceException(
          "You have already created your " + numberMaxApplications + " apps into the Cloud");
    }

    try {
      if (checkAppExist(application.getUser(), application.getName())) {
        throw new CheckException(messageSource.getMessage("app.exists", null, locale));
      }
      if (imageService.findByName(serverName) == null)
        throw new CheckException(messageSource.getMessage("image.not.found", null, locale));
      imageService.findByName(serverName);

    } catch (PersistenceException e) {
      logger.error("ApplicationService Error : Create Application" + e);
      throw new ServiceException(e.getLocalizedMessage(), e);
    }
  }
  /**
   * Add git container to application associated to server
   *
   * @param application
   * @return
   * @throws ServiceException
   * @throws CheckException
   */
  private Module addGitContainer(Application application, String tagName)
      throws ServiceException, CheckException {

    Module moduleGit = ModuleFactory.getModule("git");
    // todo : externaliser la variable
    String containerGitAddress = "/cloudunit/git/.git";

    try {
      // Assign fixed host ports for forwarding git ports (22)
      Map<String, String> mapProxyPorts = portUtils.assignProxyPorts(application);
      String freeProxySshPortNumber = mapProxyPorts.get("freeProxySshPortNumber");

      // Creation of git container fo application
      moduleGit.setName("git");
      moduleGit.setImage(imageService.findByName("git"));
      moduleGit.setApplication(application);

      moduleGit.setSshPort(freeProxySshPortNumber);
      moduleGit = moduleService.initModule(application, moduleGit, tagName);

      application.getModules().add(moduleGit);
      application.setGitContainerIP(moduleGit.getContainerIP());

      application.setGitSshProxyPort(freeProxySshPortNumber);

      // Update GIT respository informations in the current application
      application.setGitAddress(
          "ssh://"
              + AlphaNumericsCharactersCheckUtils.convertToAlphaNumerics(
                  application.getUser().getLogin())
              + "@"
              + application.getName()
              + "."
              + application.getSuffixCloudUnitIO().substring(1)
              + ":"
              + application.getGitSshProxyPort()
              + containerGitAddress);

      moduleGit.setStatus(Status.START);
      moduleGit = moduleService.update(moduleGit);

    } catch (UnsupportedEncodingException e) {
      moduleGit.setStatus(Status.FAIL);
      logger.error("Error :  Error during persist git module " + e);
      throw new ServiceException(e.getLocalizedMessage(), e);
    }
    return moduleGit;
  }
  @Override
  @Transactional(rollbackFor = ServiceException.class)
  public Application create(String applicationName, String login, String serverName, String tagName)
      throws ServiceException, CheckException {

    // if tagname is null, we prefix with a ":"
    if (tagName != null) {
      tagName = ":" + tagName;
    }
    if (applicationName != null) {
      applicationName = applicationName.toLowerCase();
    }

    logger.info("--CALL CREATE NEW APP--");
    Application application = new Application();

    logger.info("applicationName = " + applicationName + ", serverName = " + serverName);

    User user = authentificationUtils.getAuthentificatedUser();

    // For cloning management
    if (tagName != null) {
      application.setAClone(true);
    }

    application.setName(applicationName);
    application.setUser(user);
    application.setModules(new ArrayList<>());

    // verify if application exists already
    this.checkCreate(application, serverName);

    // todo : use a session flag
    application.setStatus(Status.PENDING);

    application = this.saveInDB(application);
    serverService.checkMaxNumberReach(application);

    String subdomain = System.getenv("CU_SUB_DOMAIN") == null ? "" : System.getenv("CU_SUB_DOMAIN");

    List<Image> imagesEnabled = imageService.findEnabledImages();
    List<String> imageNames = new ArrayList<>();
    for (Image image : imagesEnabled) {
      imageNames.add(image.getName());
    }

    if (!imageNames.contains(serverName)) {
      throw new CheckException(messageSource.getMessage("server.not.found", null, locale));
    }

    try {
      // BLOC APPLICATION
      application.setDomainName(subdomain + suffixCloudUnitIO);
      application = applicationDAO.save(application);
      application.setManagerIp(dockerManagerIp);
      application.setJvmRelease(javaVersionDefault);
      application.setRestHost(restHost);
      logger.info(application.getManagerIp());

      // BLOC SERVER
      Server server = ServerFactory.getServer(serverName);
      // We get image associated to server
      Image image = imageService.findByName(serverName);
      server.setImage(image);
      server.setApplication(application);
      server.setName(serverName);
      server = serverService.create(server, tagName);

      List<Server> servers = new ArrayList<>();
      servers.add(server);
      application.setServers(servers);

      // BLOC MODULE
      Module moduleGit = this.addGitContainer(application, tagName);
      application.getModules().add(moduleGit);
      application.setGitContainerIP(moduleGit.getContainerIP());

      // Persistence for Application model
      application = applicationDAO.save(application);

      // Copy the ssh key from the server to git container to be able to deploy war with gitpush
      // During clone processus, env variables are not updated. We must wait for a restart before
      // to copy the ssh keys for git push
      if (tagName == null) {
        this.sshCopyIDToServer(application, user);
      }

    } catch (DataAccessException e) {
      throw new ServiceException(e.getLocalizedMessage(), e);
    }

    logger.info("" + application);
    logger.info(
        "ApplicationService : Application " + application.getName() + " successfully created.");

    return application;
  }