/*
 * @(#)PNGStructView.java  1.0  2010-06-24
 *
 * Copyright (c) 2010 Werner Randelshofer, Immensee, Switzerland.
 * All rights reserved.
 *
 * You may not use, copy or modify this file, except in compliance with the
 * license agreement you entered into with Werner Randelshofer.
 * For details see accompanying license terms.
 */
package ch.randelshofer.view;

import org.monte.media.ParseException;
import org.monte.media.binary.*;
import ch.randelshofer.util.*;

import java.awt.*;
import java.io.*;
import java.text.NumberFormat;

import javax.activation.DataHandler;

import javax.activation.FileDataSource;
import javax.imageio.stream.FileCacheImageInputStream;
import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStream;
import javax.swing.*;
import javax.swing.tree.*;

/**
 * Displays the structure of a PNG file and parses well known chunks.
 * <a href="http://www.libpng.org/pub/png/spec/iso/index-noobject.html"
 * >http://www.libpng.org/pub/png/spec/iso/index-noobject.html</a>
 *
 * @author  Werner Randelshofer
 * @version 1.0 2010-06-24 Created.
 */
public class PNGStructView extends AbstractStructView {

    private InputStream inputStream;

    protected static class PNGChunk
            implements AbstractStructView.StructNode {

        private static NumberFormat numFormat = NumberFormat.getInstance();
        private PNGModel model;
        private DefaultMutableTreeNode node;
        private String id;
        private int crc;
        private long size;
        private long offset;
        private byte[] data;
        private int indexInParent;
        private File file;

        public PNGChunk(PNGModel model, String id, long offset, long size, int crc) {
            this.model = model;
            this.id = id;
            this.size = size;
            this.offset = offset;
            this.crc = crc;
        }

        public PNGChunk(PNGModel model, String id, long offset, long size, byte[] data, int crc) {
            this.model = model;
            this.id = id;
            this.size = size;
            this.offset = offset;
            this.data = data;
            this.crc = crc;
        }

        public PNGChunk(PNGModel model, String id, long offset, long size, File file, int crc) {
            this.model = model;
            this.id = id;
            this.size = size;
            this.offset = offset;
            this.file = file;
            this.crc = crc;
        }

        @Override
        public byte[] getRawData(long offset, int len) {
            if (len <= 0) {
                return new byte[0];
            }
            if (data != null) {
                if (offset == 0 && len == data.length) {
                    return data;
                } else {
                    byte[] bytes = new byte[len];
                    System.arraycopy(data, 0, bytes, (int) offset, Math.min(data.length, len));
                    return bytes;
                }
            } else if (file != null) {
                byte[] bytes = new byte[len];
                RandomAccessFile raf = null;
                try {
                    raf = new RandomAccessFile(file, "r");
                    raf.seek(this.offset + offset);
                    raf.read(bytes);
                } catch (IOException e) {
                    e.printStackTrace();
                    file = null;
                } finally {
                    if (raf != null) {
                        try {
                            raf.close();
                        } catch (IOException ex) {
                            ex.printStackTrace();
                            file = null;
                        }
                    }
                }
                return bytes;
            }
            return null;
        }

        @Override
        public java.util.List<BinaryPanel.Highlight> getRawDataHighlights() {
            return null;
        }

        @Override
        public long getSize() {
            return size;
        }

        @Override
        public long getOffset() {
            return offset;
        }

        @Override
        public String getName() {
            return model.getName(this);
        }

        @Override
        public String getId() {
            return id;
        }

        @Override
        public String getDescription() {
            return model.getDescription(this);
        }

        @Override
        public StructTableModel getStructTableModel() {
            return model.getStructTableModel(this);
        }

        @Override
        public String toString() {
            StringBuffer b = new StringBuffer();
            /*String addr = Long.toHexString(pos);
            b.append("00000000".substring(addr.length()));
            b.append(addr);
            b.append("> ");
             */ b.append(id);
            b.append(' ');
            b.append(numFormat.format(size));
            return b.toString();
        }

        @Override
        public int getIndexInParent() {
            return indexInParent;
        }

        public void setIndexInParent(int cc) {
            indexInParent = cc;
        }

        @Override
        public boolean hasRawData() {
            return data != null || file != null;
        }

        @Override
        public File getFile() {
            return file;
        }
    }

    protected static class PNGModel extends DefaultTreeModel {

        private static StructParser structParser;

        public PNGModel(File file, InputStream in)
                throws IOException {
            super(new DefaultMutableTreeNode());
            DefaultMutableTreeNode root = (DefaultMutableTreeNode) getRoot();

            if (structParser == null) {
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(
                            new InputStreamReader(
                            PNGStructView.class.getResourceAsStream("PNGChunks.txt"), "UTF-8"));
                    structParser = (reader == null) ? new StructParser() : new StructParser(reader);
                } catch (ParseException e) {
                    throw new InternalError(e.toString());
                } finally {
                    if (reader != null) {
                        reader.close();
                    }
                }
            }

            ImageInputStream iin = null;
            try {
                iin = (file == null) ? new FileCacheImageInputStream(in, null) : new FileImageInputStream(file);
                decode(file, iin, root, Long.MAX_VALUE, 0);
            } catch (EOFException e) {
                // It's ok to encounter an EOF exception because QuickTime
                // does not have a marker that tells us when the file is finished.
            } catch (ParseException e) {
                root.add(new DefaultMutableTreeNode(new PNGStructView.PNGChunk(this, e.toString(), 0, 8, 0)));
            } finally {
                IOException ex = null;
                try {
                    iin.close();
                } catch (IOException e) {
                    ex = e;
                }
                try {
                    in.close();
                } catch (IOException e) {
                    ex = e;
                }
                if (ex != null) {
                    throw ex;
                }
            }
        }

        public String getName(PNGChunk atom) {
            String id = atom.getId();
            String name = structParser.getName(id);

            return (name == null) ? id : name;
        }

        public String getDescription(PNGChunk chunk) {
            String id = chunk.getId();
            StringBuilder buf = new StringBuilder();
            String desc = structParser.getDescription(id);
            if (desc != null) {
                buf.append(desc);
                buf.append("<br><br>");
            }
            buf.append("Chunk Type: ");
            buf.append((id.charAt(0) <= 'Z') ? "critical" : "ancillary");
            buf.append(", ");
            buf.append((id.charAt(1) <= 'Z') ? "public" : "private");
            buf.append(", ");
            buf.append((id.charAt(3) <= 'Z') ? "unsafe to copy" : "save to copy");
            buf.append(". CRC: 0x");
            buf.append(Integer.toHexString(chunk.crc));
            return buf.toString();
        }

        public StructTableModel getStructTableModel(PNGChunk chunk) {


            if (structParser.isTypeDeclared(chunk.getId())) {
                try {
                    byte[] data = chunk.getRawData(0, (int) chunk.getSize());
                    return (data == null) ? null : structParser.readStruct(chunk.getId(), data);
                } catch (IOException e) {
                    return null;
                }
            } else {
                return null;
            }
        }

        private void decode(File file, ImageInputStream in, DefaultMutableTreeNode parentNode, long remainingSize, long pos)
                throws IOException, ParseException {
            DefaultMutableTreeNode node;

            { // Decode magic
                long magic = in.readLong();
                if (magic != 0x89504e470d0a1a0aL) {
                    throw new IOException("Bad PNG magic 0x" + Long.toHexString(magic));
                }
            }

            long offset = 8;
            while (true) { // Decode chunks
                long length;
                try {
                    length = in.readUnsignedInt();
                } catch (EOFException e) {
                    break;
                }
                int type = in.readInt();
                offset += 8;
                long skipped = in.skipBytes(length);
                if (skipped != length) {
                    throw new IOException("Skip " + length + " only skipped " + skipped + " bytes at offset " + offset);
                }
                offset += length;
                int crc = in.readInt();
                offset += 4;

                PNGChunk chunk = new PNGChunk(this, typeToString(type), offset - length - 4, length, file, crc);
                parentNode.add(new DefaultMutableTreeNode(chunk));
            }
        }

        /**
         * Convert an integer Atom identifier to String.
         *
         * @param  ID to be converted.
         * @return  String representation of the ID.
         */
        private String typeToString(int type) {
            byte[] bytes = new byte[4];

            bytes[0] = (byte) (type >>> 24);
            bytes[1] = (byte) (type >>> 16);
            bytes[2] = (byte) (type >>> 8);
            bytes[3] = (byte) (type >>> 0);
            try {

                return new String(bytes, "ASCII");
            } catch (UnsupportedEncodingException ex) {
                return new String(bytes);
            }
        }
    }

    /** Initializes the Form */
    public PNGStructView() {
        //initComponents ();
    }

    @Override
    public void setCommandContext(String verb, DataHandler dh)
            throws IOException {
        final File file;
        if (dh.getDataSource() instanceof FileDataSource) {
            file = ((FileDataSource) dh.getDataSource()).getFile();
        } else {
            file = null;
        }
        inputStream = new BufferedInputStream(dh.getInputStream());
        setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

        ch.randelshofer.gui.SwingWorker worker = new ch.randelshofer.gui.SwingWorker() {

            @Override
            public Object construct() {
                Object result;

                try {
                    result = new PNGModel(file, inputStream);
                } catch (Exception e) {
                    result = e;
                }
                try {
                    inputStream.close();
                } catch (IOException e) {
                }

                return result;
            }

            @Override
            public void finished() {
                Object result = get();
                if (result instanceof PNGModel) {
                    getTree().setModel((PNGModel) result);
                } else {
                    removeAll();
                    add(new JLabel(result.toString()));
                    ((Throwable) result).printStackTrace();
                }
                setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
                getTree().expandRow(0);
                getTree().setSelectionRow(0);
                getSplitPane().setDividerLocation(getTree().getPreferredSize().width + 20);
            }
        };
        worker.start();
    }

    @Override
    public void dispose() {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
            }
            inputStream = null;
        }
    }

    @Override
    public String toString() {
        return "QuickTime Struct View";
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the FormEditor.
     */
    private void initComponents () {//GEN-BEGIN:initComponents
        setLayout (new java.awt.BorderLayout ());

    }//GEN-END:initComponents
// Variables declaration - do not modify//GEN-BEGIN:variables
// End of variables declaration//GEN-END:variables
}
