package com.axwave.ak.programmingtask.server.service;

import com.axwave.ak.programmingtask.transport.model.Metadata;
import com.axwave.ak.programmingtask.transport.model.SoundSample;
import com.axwave.ak.programmingtask.transport.service.AudioService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@Service
public class AudioServiceImpl implements AudioService {
    private static final Logger log = Logger.getLogger(AudioServiceImpl.class);

    private final String safeFolderPath;

    public AudioServiceImpl(@Value("#{${save.folder.path} ?: systemProperties['user.dir']}") String saveFolderPath) {
        this.safeFolderPath = saveFolderPath;
    }

    public Metadata saveSoundSample(SoundSample sample) {
        log.debug("received sound sample: " + sample);

        saveSoundSampleToFolder(sample);

        Metadata echoResponse = sample;
        return echoResponse;
    }

    private void saveSoundSampleToFolder(SoundSample sample) {
        File saveFolder = new File(safeFolderPath + "/" + sample.getFormat().getEncodingName());

        if (!saveFolder.exists()) {
            saveFolder.mkdir();
        }

        String filePath = saveFolder.getPath() + "/" + sample.getTimestamp() + sample.getFormat().getFileExtension();
        File file = new File(filePath);
        log.debug("write sample to file: " + file.getPath());

        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(sample.getSample());
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (IOException e) {
            log.error("Error occurred during writing sound sample to file " + file.getPath(), e);
        }
    }
}

@@ -44,24 +44,91 @@
 r.service;%0A%0A
+import com.axwave.ak.programmingtask.transport.format.SoundFormat;%0A
 import com.a
@@ -1219,157 +1219,56 @@
 r = 
-new File(safeFolderPath + %22/%22 + sample.getFormat().getEncodingName());%0A%0A        if (!saveFolder.exists()) %7B%0A            saveFolder.mkdir();%0A        %7D
+getSaveFolderForSoundFormat(sample.getFormat());
 %0A%0A  
@@ -1855,11 +1855,286 @@
  %7D%0A    %7D
+%0A%0A    private File getSaveFolderForSoundFormat(SoundFormat soundFormat) %7B%0A        File saveFolder = new File(safeFolderPath + %22/%22 + soundFormat.getEncodingName());%0A%0A        if (!saveFolder.exists()) %7B%0A            saveFolder.mkdir();%0A        %7D%0A        return saveFolder;%0A    %7D
 %0A%7D%0A

Refactor of getting directory for sound format for saving samples