/*
 * @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.nio.file.NotDirectoryException;
import java.nio.file.attribute.FileTime;
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.generic.ValueUtils;
import net.ranides.assira.io.IOHandle;
import net.ranides.assira.io.InputStreamWrapper;
import net.ranides.assira.io.uri.*;
import net.ranides.assira.text.StringTraits;
import net.ranides.assira.text.StringUtils;


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 String[] split(URI uri) {
        String file = URIUtils.getFile(uri);
        return StringUtils.removePrefix(file,"file:").split("!/", 2);
    }

    private static URI concat(File jar, String file) {
        return new URIBuilder().scheme("jar").path(jar + "!/" + 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.getParam(uri, "charset"), split(uri));
        }

        private CJarHandle(URI uri, Optional<String> charset, String... path) {
            this.uri = uri;
            this.jar = new File(path[0]);
            this.file = path[1];
            this.charset = Charset.forName(charset.orElse("UTF-8"));
            this.text = charset.isPresent();
            this.entry = IOHandle.shared(() -> {
                ZipEntry edir = man.shared(jar).getEntry(file+"/");
                if(edir != null) {
                    return edir;
                }
                return man.shared(jar).getEntry(file);
            });
            man.open(jar);

        }
        
        public CJarHandle(File jar, String file) {
            this(concat(jar, file), Optional.empty(), jar.toString(), file);
        }
        
        @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() {
            return uri;
        }

        @Override
        public Charset charset() throws IOException {
            return charset;
        }
        
        @Override
        public boolean exists() throws IOException {
            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();
            FileTime ft;
            switch(ut) {
                case ACCESSED:
                    ft = attr.getLastAccessTime();
                    break;
                case CREATED:
                    ft = attr.getCreationTime();
                    break;
                case MODIFIED:
                    ft = attr.getLastModifiedTime();
                    break;
                default:
                    throw new UnsupportedOperationException("Not supported attribute: " + ut);
            }
            if(null == ft) {
                throw new UnsupportedOperationException("Unknown value of attribute: " + ut);
            }
            return ft.toInstant();
        }

        @Override
        public long size() throws IOException {
            return info().isDirectory() ? scan().size() : info().getSize();
        }
        
        @Override
        public URIHandle parent() throws IOException {
            return new CJarHandle(jar, ValueUtils.or(new File(file).getParent(),""));
        }
        
        @Override
        public CQuery<URIHandle> scan() throws IOException {
            if(!file.isEmpty() && !info().isDirectory() ) {
                throw new NotDirectoryException(file);
            }
            return CQueryBuilder
                .fromStream(() -> man.shared(jar).stream().filter(e -> isChildren(StringUtils.trim(file,'/'), e)))
                .map(e -> new CJarHandle(jar, e.getName()));
        }

        private boolean isChildren(String parent, ZipEntry e) {
            String name = StringUtils.trim(e.getName(),'/');
            if( parent.equals(name)) {
                return false;
            }
            if( !name.startsWith(parent)) {
                return false;
            }
            String subpath = StringUtils.trim(name.substring(file.length()),'/');
            return !StringTraits.contains(subpath,'/');
        }

        @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);
        }
        
    }
}
