package org.openlmis.fulfillment.service;

import org.apache.camel.Exchange;
import org.apache.camel.ProducerTemplate;
import org.openlmis.fulfillment.domain.FacilityFtpSetting;
import org.openlmis.fulfillment.domain.Order;
import org.openlmis.fulfillment.repository.FacilityFtpSettingRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.Path;

@Component
public class OrderFtpSender implements OrderSender {
  private static final Logger LOGGER = LoggerFactory.getLogger(OrderFtpSender.class);

  @Autowired
  private ProducerTemplate producerTemplate;

  @Autowired
  private OrderStorage orderStorage;

  @Autowired
  private FacilityFtpSettingRepository facilityFtpSettingRepository;

  @Override
  public boolean send(Order order) throws OrderSenderException {
    Path path = orderStorage.getOrderAsPath(order);
    FacilityFtpSetting setting = facilityFtpSettingRepository
        .findFirstByFacilityId(order.getSupplyingFacilityId());

    try {
      String endpointUri = createEndpointUri(setting);
      File file = path.toFile();
      producerTemplate.sendBodyAndHeader(endpointUri, file, Exchange.FILE_NAME, file.getName());
    } catch (Exception exp) {
      LOGGER.error(
          "Can't transfer CSV file {} related with order {} to the FTP server",
          path, order.getId(), exp
      );

      return false;
    }

    return true;
  }

  private String createEndpointUri(FacilityFtpSetting setting) {
    return setting.getProtocol() + "://" + setting.getUsername() + "@" + setting.getServerHost()
        + ":" + setting.getServerPort() + "/" + setting.getRemoteDirectory() + "?password="
        + setting.getPassword() + "&passiveMode=" + setting.isPassiveMode();
  }
}

@@ -507,16 +507,48 @@
 le.Path;
+%0Aimport java.text.MessageFormat;
 %0A%0A@Compo
@@ -692,16 +692,127 @@
 lass);%0A%0A
+  private static final String CAMEL_FTP_PATTERN =%0A      %22%7B0%7D://%7B1%7D@%7B2%7D:%7B3%7D/%7B4%7D?password=%7B5%7D&passiveMode=%7B6%7D%22;%0A%0A
   @Autow
@@ -1747,16 +1747,64 @@
  return 
+MessageFormat.format(CAMEL_FTP_PATTERN,%0A        
 setting.
@@ -1820,18 +1820,17 @@
 ol()
- + %22://%22 +
+,%0A       
  set
@@ -1851,16 +1851,17 @@
 me()
- + %22@%22 +
+,%0A       
  set
@@ -1880,24 +1880,25 @@
 erHost()
+,
 %0A       
  + %22:%22 +
@@ -1893,16 +1893,8 @@
     
- + %22:%22 +
  set
@@ -1917,16 +1917,17 @@
 rt()
- + %22/%22 +
+,%0A       
  set
@@ -1955,31 +1955,17 @@
 ry()
- + %22?password=%22
+,
 %0A       
  + s
@@ -1960,18 +1960,16 @@
 %0A       
- +
  setting
@@ -1986,28 +1986,17 @@
 rd()
- + %22&passiveMode=%22 +
+,%0A       
  set
@@ -2015,16 +2015,17 @@
 veMode()
+)
 ;%0A  %7D%0A%7D%0A

Revert "Removed hard-coded password"