/*
 * @author Ranides Atterwim <ranides@gmail.com>
 * @copyright Ranides Atterwim
 * @license WTFPL
 * @url http://ranides.net/projects/assira
 */
package net.ranides.assira.io.uri.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.Charset;
import java.time.Instant;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import net.ranides.assira.collection.query.CQuery;
import net.ranides.assira.collection.query.CQueryBuilder;
import net.ranides.assira.io.IOHandle;
import net.ranides.assira.io.InputStreamWrapper;
import net.ranides.assira.io.uri.URIBuilder;
import net.ranides.assira.io.uri.URIFlags;
import net.ranides.assira.io.uri.URIHandle;
import net.ranides.assira.io.uri.URIHandler;
import net.ranides.assira.io.uri.URIResolver;
import net.ranides.assira.io.uri.URITime;
import net.ranides.assira.io.uri.URIUtils;


// @todo (assira #1) uri: JAR Handler
public class CJarHandler implements URIHandler {
    
    private final JARManager man = new JARManager();
    
    private final URIResolver resolver;
    
    public CJarHandler() {
        this.resolver = URIResolver.DEFAULT;
    }

    public CJarHandler(URIResolver resolver) {
        this.resolver = resolver;
    }

    @Override
    public URIHandle resolve(URI uri) throws IOException {
        return new CJarHandle(uri);
    }

    @Override
    public Collection<String> schemes() {
        return Arrays.asList("jar");
    }
    
    private static URI concat(File jar, String file) {
        return new URIBuilder()
            .scheme("jar")
            .path(jar.toString())
            .param("file", file)
            .build();
    }
    
    private class CJarHandle extends CHandle {
        
        public final URI uri;
        public final File jar;
        public final String file;
        public final Charset charset;
        public final boolean text;
        
        public final IOHandle<ZipEntry> entry;

        public CJarHandle(URI uri) {
            this(uri, URIUtils.getFile(uri), URIUtils.getParam(uri, "file").get(), URIUtils.getParam(uri, "charset"));
        }

        public CJarHandle(URI uri, File jar, String file, Optional<String> charset) {
            this.uri = uri;
            this.jar = jar;
            this.file = file;
            this.charset = Charset.forName(charset.orElse("UTF-8"));
            this.text = charset.isPresent();
            this.entry = IOHandle.shared(() -> man.shared(jar).getEntry(file));
            man.open(jar);

        }
        
        public CJarHandle(File jar, String file) {
            this(concat(jar, file), jar, file, Optional.empty());
        }
        
        @Override
        public void close() throws IOException {
            man.close(jar);
        }
        
        @Override
        public URIResolver resolver() {
            return CJarHandler.this.resolver;
        }
        
        @Override
        public String scheme() throws IOException {
            return "jar";
        }

        @Override
        public URI uri() throws IOException {
            return uri;
        }

        @Override
        public Charset charset() throws IOException {
            return charset;
        }
        
        @Override
        public boolean exists() throws IOException {
            man.shared(jar).getEntry(file);
            return null != entry.get();
        }
        
        @Override
        public Set<URIFlags> flags() throws IOException {
            ZipEntry attr = entry.get();
            Set<URIFlags> flags = URIFlags.collect();
            
            if(null == attr) {
                return flags;
            }
            if(attr.isDirectory()) {
                flags.add(URIFlags.DIR);
            } else {
                flags.add(URIFlags.FILE);
                flags.add(URIFlags.READABLE);
            }
            if(-1 != attr.getSize()) {
                flags.add(URIFlags.SIZE);
            }
            if(text) {
                flags.add(URIFlags.TEXT);
            } else {
                flags.add(URIFlags.BINARY);
            }
            return flags;
        }
        
        @Override
        public Instant time(URITime ut) throws IOException {
            ZipEntry attr = info();
            
            switch(ut) {
                case ACCESSED:
                    return attr.getLastAccessTime().toInstant();
                case CREATED:
                    return attr.getCreationTime().toInstant();
                case MODIFIED:
                    return attr.getLastModifiedTime().toInstant();
                case META_MODIFIED:
                    throw new UnsupportedOperationException("Not supported attribute: META_MODIFIED");
                default:
                    throw new UnsupportedOperationException("Not supported attribute: " + ut);
            }
        }

        @Override
        public long size() throws IOException {
            return info().getSize();
        }
        
        @Override
        public URIHandle parent() throws IOException {
            return new CJarHandle(jar, new File(file).getParent());
        }
        
        @Override
        public CQuery<URIHandle> scan() throws IOException {
            return CQueryBuilder
                .fromStream(() -> man.shared(jar).stream().filter(e -> e.getName().startsWith(file)))
                .map(e -> new CJarHandle(jar, e.getName()));
        }

        @Override
        public InputStream istream() throws IOException {
            man.open(jar);
            InputStream is = man.shared(jar).getInputStream(entry.get());
            return new InputStreamWrapper(is){
                @Override
                public void close() throws IOException {
                    super.close();
                    man.close(jar);
                }
            };
        }
        
        private ZipEntry info() throws FileNotFoundException, IOException {
            ZipEntry attr = entry.get();
            if(null == attr) {
                throw new FileNotFoundException("File not found: " + file);
            }
            return attr;
        }
        
    }
    
    private static final class JARManager extends CHandleManager<File, ZipFile> {
        
        @Override
        protected void disconnect(ZipFile zip) throws IOException {
            zip.close();
        }

        @Override
        protected void reset(ZipFile zip) throws IOException {
            // do nothing
        }

        @Override
        protected ZipFile connect(File path) throws IOException {
            return new ZipFile(path);
        }
        
    }
}
