/*
 * @(#)NeoChromeStructView.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 ch.randelshofer.io.CopyingInputStream;
import org.monte.media.binary.*;
import ch.randelshofer.util.*;

import java.awt.*;
import java.io.*;

import javax.activation.DataHandler;

import javax.swing.*;
import javax.swing.tree.*;

/**
 * Displays the structure of a NeoChrome image file and parses well known chunks.
 * <a href="http://wiki.multimedia.cx/index.php?title=Neochrome"
 * >http://wiki.multimedia.cx/index.php?title=Neochrome</a>
 *
 * @author  Werner Randelshofer
 * @version 1.0 2010-06-24 Created.
 */
public class NeoChromeStructView extends AbstractStructView {

    private InputStream inputStream;
    private final static String HEADER_ID = "Header";
    private final static String DATA_ID = "Data";

    protected static class NeoNode
            implements AbstractStructView.StructNode {

        private NeoModel model;
        private String id;
        private byte[] data;
        private int indexInParent = -1;
        private int offset;
        private long size;

        public NeoNode(NeoModel model, String id, int offset, byte[] data) {
            this.model = model;
            this.id = id;
            this.offset = offset;
            this.data = data;
        }

        @Override
        public String getName() {
            if (indexInParent == -1) {
                return model.getName(id);
            } else {
                return model.getName(id) + " " + indexInParent;
            }
        }

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

        @Override
        public byte[] getRawData(long offset, int length) {
            if (data == null || offset == 0 && length == data.length) {
                return data;
            } else {
                byte[] bytes = new byte[length];
                System.arraycopy(data, 0, bytes, (int) offset, length);
                return bytes;
            }
        }

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

        @Override
        public String toString() {
            return getName();
        }

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

        @Override
        public long getSize() {
            return data==null?size:data.length;
        }
        public void setSize(long size) {
            this.size=size;
        }

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

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

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

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

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

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

    protected static class NeoModel
            extends DefaultTreeModel {

        private static StructParser structParser;

        public NeoModel(InputStream in)
                throws IOException {
            super(new DefaultMutableTreeNode());
            DefaultMutableTreeNode root = (DefaultMutableTreeNode) getRoot();

            // Parse the CyberPaintSeqStruct's definitions.
            if (structParser == null) {
                BufferedReader reader = null;
                try {
                    reader = new BufferedReader(
                            new InputStreamReader(
                            NeoChromeStructView.class.getResourceAsStream("NeoChromeStructs.txt")));
                    structParser = (reader == null) ? new StructParser() : new StructParser(reader);
                } catch (NullPointerException e) {
                    InternalError error = new InternalError(e.toString());
                    error.initCause(e);
                    throw error;
                } catch (ParseException e) {
                    InternalError error = new InternalError(e.toString());
                    error.initCause(e);
                    throw error;
                } finally {
                    if (reader != null) {
                        reader.close();
                    }
                }
            }

            // Parse the input stream
            if (!(in instanceof BufferedInputStream)) {
                in = new BufferedInputStream(in);
            }
            ByteArrayOutputStream buf = new ByteArrayOutputStream();
            CopyingInputStream cin = new CopyingInputStream(in, buf);
            DataInputStream din = new DataInputStream(cin);

            // Parse the Header
            {
                buf.reset();
                din.skipBytes(128);
                NeoNode node = new NeoNode(this, HEADER_ID, 0, buf.toByteArray());
                DefaultMutableTreeNode treeNode = new DefaultMutableTreeNode(node);
                root.add(treeNode);
            }

            // Parse the Data
            {
                buf.reset();
                din.skipBytes(32000);
                NeoNode node = new NeoNode(this, DATA_ID, 128, buf.toByteArray());
                DefaultMutableTreeNode treeNode = new DefaultMutableTreeNode(node);
                root.add(treeNode);
            }

        }

        public StructTableModel getStructTableModel(NeoNode node) {
            try {
                byte[] data = node.getRawData(0, (int) node.getSize());
                if (data == null) {
                    return null;
                }
                return structParser.readStruct(node.id, data);
            } catch (IOException e) {
                //e.printStackTrace();
                return null;
            }
        }

        public String getName(String id) {
            return structParser.getName(id);
        }

        public String getDescription(String id) {
            return structParser.getDescription(id);
        }
    }

    /** Creates new form PictStructView */
    public NeoChromeStructView() {
        //initComponents();
    }

    @Override
    public void setCommandContext(String verb, DataHandler dh)
            throws IOException {
        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 NeoModel(inputStream);
                } catch (IOException e) {
                    result = e;
                }
                try {
                    inputStream.close();
                } catch (IOException e) {
                }

                return result;
            }

            @Override
            public void finished() {
                Object result = get();
                if (result instanceof NeoModel) {
                    getTree().setModel((NeoModel) result);
                } else {
                    removeAll();
                    add(new JLabel(result.toString()));
                    if (result instanceof Throwable) {
                        ((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;
        }
    }

    /** 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 Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    // End of variables declaration//GEN-END:variables
}
