/*
 *
 * MIT License
 *
 * Copyright (c) 2020. Brockmann Consult GmbH (info@brockmann-consult.de)
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 *
 */

package com.bc.zarr.storage;

import com.bc.zarr.ZarrConstants;
import com.bc.zarr.ZarrUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.TreeSet;
import java.util.stream.Collectors;

public class FileSystemStore implements Store {

    private Path root;

    public FileSystemStore(String path, FileSystem fileSystem) {
        if (fileSystem == null) {
            root = Paths.get(path);
        } else {
            root = fileSystem.getPath(path);
        }
    }

    public FileSystemStore(Path rootPath) {
        root = rootPath;
    }

    @Override
    public InputStream getInputStream(String key) throws IOException {
        final Path path = root.resolve(key);
        if (Files.isReadable(path)) {
            return Files.newInputStream(path);
        } else {
            return null;
        }
    }

    @Override
    public OutputStream getOutputStream(String key) throws IOException {
        final Path filePath = root.resolve(key);
        final Path dir = filePath.getParent();
        Files.createDirectories(dir);
        return Files.newOutputStream(filePath);
    }

    @Override
    public void delete(String key) throws IOException {
        final Path toBeDeleted = root.resolve(key);
        if (Files.isDirectory(toBeDeleted)) {
            ZarrUtils.deleteDirectoryTreeRecursively(toBeDeleted);
        }
        if (Files.exists(toBeDeleted)){
            Files.delete(toBeDeleted);
        }
        if (Files.exists(toBeDeleted)|| Files.isDirectory(toBeDeleted)) {
            throw new IOException("Unable to initialize " + toBeDeleted.toAbsolutePath().toString());
        }
    }

    @Override
    public TreeSet<String> getArrayKeys() throws IOException {
        return getKeysFor(ZarrConstants.FILENAME_DOT_ZARRAY);
    }

    @Override
    public TreeSet<String> getGroupKeys() throws IOException {
        return getKeysFor(ZarrConstants.FILENAME_DOT_ZGROUP);
    }

    private TreeSet<String> getKeysFor(String suffix) throws IOException {
        return  Files.walk(root)
                .filter(path -> path.getFileName().toString().endsWith(suffix))
                .map(path -> root.relativize(path.getParent()).toString())
                .collect(Collectors.toCollection(TreeSet::new));
    }
}

@@ -1269,16 +1269,91 @@
 Utils;%0A%0A
+import java.io.ByteArrayInputStream;%0Aimport java.io.ByteArrayOutputStream;%0A
 import j
@@ -1669,22 +1669,36 @@
 private 
-Path r
+final Path internalR
 oot;%0A%0A  
@@ -1802,25 +1802,33 @@
             
-r
+internalR
 oot = Paths.
@@ -1863,25 +1863,33 @@
             
-r
+internalR
 oot = fileSy
@@ -1977,17 +1977,25 @@
         
-r
+internalR
 oot = ro
@@ -2116,25 +2116,33 @@
 Path path = 
-r
+internalR
 oot.resolve(
@@ -2197,32 +2197,89 @@
         
-return Files.new
+byte%5B%5D bytes = Files.readAllBytes(path);%0A            return new ByteArray
 InputStr
@@ -2282,20 +2282,21 @@
 tStream(
-path
+bytes
 );%0A     
@@ -2295,36 +2295,25 @@
 );%0A        %7D
- else %7B%0A    
+%0A
         retu
@@ -2321,26 +2321,16 @@
 n null;%0A
-        %7D%0A
     %7D%0A%0A 
@@ -2394,37 +2394,321 @@
 ng key) 
-throws IOException %7B%0A
+%7B%0A        return new ByteArrayOutputStream() %7B%0A            private boolean closed = false;%0A%0A            @Override%0A            public void close() throws IOException %7B%0A                try %7B%0A                    if (!closed) %7B%0A                        final byte%5B%5D bytes = this.toByteArray();%0A                
         
@@ -2729,17 +2729,25 @@
 ePath = 
-r
+internalR
 oot.reso
@@ -2768,131 +2768,420 @@
     
-final Path dir = filePath.getParent();%0A        Files.createDirectories(dir);%0A        return Files.newOutputStream(filePath)
+                if (Files.exists(filePath)) %7B%0A                            Files.delete(filePath);%0A                        %7D else %7B%0A                            Files.createDirectories(filePath.getParent());%0A                        %7D%0A                        Files.write(filePath, bytes);%0A                    %7D%0A                %7D finally %7B%0A                    closed = true;%0A                %7D%0A            %7D%0A        %7D
 ;%0A  
@@ -3288,17 +3288,25 @@
 leted = 
-r
+internalR
 oot.reso
@@ -3476,16 +3476,17 @@
 eleted))
+ 
 %7B%0A      
@@ -3565,16 +3565,17 @@
 Deleted)
+ 
 %7C%7C Files
@@ -4104,17 +4104,16 @@
  return 
- 
 Files.wa
@@ -4115,17 +4115,25 @@
 es.walk(
-r
+internalR
 oot)%0A   
@@ -4238,17 +4238,25 @@
 path -%3E 
-r
+internalR
 oot.rela

use ByteArrayInput- and -OutputStream