package ervu.service.scheduler;

import java.io.IOException;
import java.util.Arrays;

import ervu.client.fileupload.WebDavClient;
import net.javacrumbs.shedlock.core.SchedulerLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

/**
 * @author gulnaz
 */
@Service
public class WebDavSchedulerService {
  private static final Logger LOGGER = LoggerFactory.getLogger(WebDavSchedulerService.class);
  private final WebDavClient webDavClient;

  @Value("${webdav.urls}")
  private String[] urls;
  @Value("${file.webdav.lifetime.seconds:300}")
  private long fileLifetime;
  @Value("${file.webdav.extensions:}")
  private String[] fileExtensions;

  public WebDavSchedulerService(WebDavClient webDavClient) {
    this.webDavClient = webDavClient;
  }

  @Scheduled(cron = "${webdav.cleanup.cron:0 0 0 * * *}")
  @SchedulerLock(name = "webDavOldFilesCleaning")
  public void deleteOldFiles() {
    Arrays.stream(urls).forEach(url -> {
      try {
        webDavClient.deleteFilesOlderThan(fileLifetime, url, fileExtensions);
      }
      catch (IOException e) {
        LOGGER.error("Failed to clean up WebDAV on {}", url, e);
      }
    });
  }
}
