/*
 * @(#)SEQStructView.java  1.1  2010-12-25
 *
 * 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 java.util.HashSet;

import javax.activation.DataHandler;

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

/**
 * Displays the structure of a CyberPaintSeq anim file and parses well known chunks.
 * <a href="http://www.atari-forum.com/wiki/index.php/ST_Picture_Formats"
 * >http://www.atari-forum.com/wiki/index.php/ST_Picture_Formats</a>
 *
 * @author  Werner Randelshofer
 * @version 1.1 2010-12-25 Renamed from CyberpaintSequnenceStructView to
 * SEQStructView.
 * <br>1.0 2010-06-23 Created.
 */
public class SEQStructView extends AbstractStructView {

    private InputStream inputStream;
    private final static String SEQ_HEADER_ID = "SeqHeader";
    private final static String FRAME_ID = "Frame";
    private final static String FRAME_OFFSETS_ID = "FrameOffsets";
    private final static String FRAME_HEADER_ID = "FrameHeader";
    private final static String FRAME_DATA_ID = "FrameData";

    protected static class SeqNode
            implements AbstractStructView.StructNode {

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

        public SeqNode(SeqModel 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) {
            byte[] d=data;
            if (d == null || offset == 0 && length == d.length) {
                return d;
            } else {
                byte[] bytes = new byte[length];
                System.arraycopy(d, 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 SeqModel
            extends DefaultTreeModel {

        private static StructParser structParser;

        public SeqModel(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(
                            SEQStructView.class.getResourceAsStream("SEQStructs.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);

            int offset = 0;
            int numberOfFrames = 0;

            // Parse the SEQ Header
            {
                buf.reset();
                int magic = din.readUnsignedShort();
                if (magic != 0xfedb && magic != 0xfedc) {
                    throw new IOException("Bad Cyberpaint Sequence magic: 0x" + Integer.toHexString(magic));
                }
                din.skipBytes(2); // version
                numberOfFrames = din.readInt();
                din.skipBytes(120);

                SeqNode node = new SeqNode(this, SEQ_HEADER_ID, offset, buf.toByteArray());
                DefaultMutableTreeNode treeNode = new DefaultMutableTreeNode(node);
                root.add(treeNode);

                offset += 128;
            }

            // Parse the Frame Offsets
            {
                buf.reset();
                din.skipBytes(4 * numberOfFrames);

                SeqNode node = new SeqNode(this, FRAME_OFFSETS_ID, offset, buf.toByteArray());
                DefaultMutableTreeNode treeNode = new DefaultMutableTreeNode(node);
                root.add(treeNode);

                offset += 4 * numberOfFrames;
            }


            for (int i = 0; i < numberOfFrames; i++) {
                SeqNode frame = new SeqNode(this, FRAME_ID, offset, null);
                DefaultMutableTreeNode frameNode = new DefaultMutableTreeNode(frame);
                frame.setIndexInParent(i);
                root.add(frameNode);



                int dataLength = 0;
                // Parse the Frame Header
                {
                    buf.reset();
                    din.skipBytes(64);
                    dataLength = din.readInt();
                    din.skipBytes(60);

                    SeqNode node = new SeqNode(this, FRAME_HEADER_ID, offset, buf.toByteArray());
                    DefaultMutableTreeNode treeNode = new DefaultMutableTreeNode(node);
                    frameNode.add(treeNode);

                    offset += 128;
                }
                // Parse the Frame Data
                {
                    buf.reset();
                    din.skipBytes(dataLength);

                    SeqNode node = new SeqNode(this, FRAME_DATA_ID, offset, buf.toByteArray());
                    DefaultMutableTreeNode treeNode = new DefaultMutableTreeNode(node);
                    frameNode.add(treeNode);

                    offset += dataLength;
                }

                frame.setSize(dataLength+128);
            }
        }

        public StructTableModel getStructTableModel(SeqNode 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 SEQStructView() {
        //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 SeqModel(inputStream);
                } catch (IOException e) {
                    result = e;
                }
                try {
                    inputStream.close();
                } catch (IOException e) {
                }

                return result;
            }

            @Override
            public void finished() {
                Object result = get();
                if (result instanceof SeqModel) {
                    getTree().setModel((SeqModel) 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
}
