/*
 * A basic implementation of the JFrame class.
 */
package usda.weru.weps.reports;

import java.awt.*;
import javax.swing.*;
import java.util.*;
import com.klg.jclass.util.swing.JCExitFrame;
import com.klg.jclass.table.*;
import com.klg.jclass.table.data.JCEditableVectorDataSource;
import de.schlichtherle.truezip.file.TFile;
import java.beans.*;
import usda.weru.weps.*;
import usda.weru.util.*;

/**
 *
 * @author maxerdwien
 */
public class RepBarPanel extends JPanel implements PropertyChangeListener {

    private static final long serialVersionUID = 1L;

    private JCEditableVectorDataSource dataSource;
    private ToolTipsTable jctable;

    /**
     *
     */
    protected String[][] tableData;
    private String measurementUnits = Util.SIUnits;

    /**
     *
     */
    protected boolean hasNorth = false;

    /**
     *
     */
    protected boolean hasSouth = false;

    /**
     *
     */
    protected boolean hasEast = false;

    /**
     *
     */
    protected boolean hasWest = false;

    /*********************************************************************** wjr */
    public RepBarPanel() {
        super();
        String[][] tableData = makeData();
        makeTable(tableData);
    }

    /*********************************************************************** wjr
     * @param sTitle */
    public RepBarPanel(String sTitle) {
        this();
//		setTitle(sTitle);

    }

    /*********************************************************************** wjr
     * @param inpDirS
     * @param title */
    public RepBarPanel(String inpDirS, String title) {
        this();

//		JL_Title.setText(title);
//		JTF_ProjectName.setText(new File(inpDirS).getParent().toString());
//		JTF_RunName.setText(new File(inpDirS).getName());
//		JTF_DateCreated.setText(new Date(inpDirF.lastModified()).toString());
    }

    /*********************************************************************** wjr
     * @param args */
    static public void main(String args[]) {
        String runDir = "";
        de.schlichtherle.truezip.file.TFile sf = null;

        WepsFileChooser wfc = new WepsFileChooser(WepsFileChooser.Filetype.RUN, runDir,
                WepsFileChooser.SELECT);
        wfc.setCurrentDirectory(new de.schlichtherle.truezip.file.TFile("c:/weps/weps1.install/projects"));
        RunFileData rfd = new RunFileData();
        if (wfc.showDialog(null) == JFileChooser.APPROVE_OPTION) {
            sf = new TFile(wfc.getSelectedFile());
            try {
                runDir = sf.getCanonicalPath();
            } catch (java.io.IOException e) {//System.err.println(
                //"Error getting canoncial path of runDir");
            }
            rfd.readRunFile(runDir);
//			rfd.showRunFileData("this is a test");
        } else {
            //System.err.println("No project directory selected");
            System.exit(1);
        }

        JCExitFrame f = new JCExitFrame("Test Report");

        RepBarPanel rbp = new RepBarPanel("Barrier Summary");
        rbp.addPropertyChangeListener(rfd);
        rbp.addPropertyChangeListener(rbp);
        rfd.fireAll(rbp);
        rbp.changes.firePropertyChange(usda.weru.util.ConfigData.Units, null, Util.USUnits);
        f.getContentPane().add(rbp);
        f.setSize(600, 400);
        f.setVisible(true);

    }

    /*********************************************************************** wjr */
    private String[][] makeData() {
        String[][] rtnStr = new String[6][];
        rtnStr[0] = new String[5];
        rtnStr[0][0] = "Barrier\nLocation";
        rtnStr[0][1] = "Barrier\nType";
        rtnStr[0][2] = "Height";
        rtnStr[0][3] = "Width";
        rtnStr[0][4] = "Porosity";
        rtnStr[1] = new String[5];
        rtnStr[1][0] = "";
        rtnStr[1][1] = "";
        rtnStr[1][2] = "m";
        rtnStr[1][3] = "m";
        rtnStr[1][4] = "frac";
        for (int linidx = 2; linidx < 6; linidx++) {
            String[] tmpStr = new String[5];
            for (int idx = 0; idx < 5; idx++) {
                tmpStr[idx] = "";
            }
            rtnStr[linidx] = tmpStr;
        }
////System.out.println("RBP_mD: " + barStr + " " + st.countTokens());
        return rtnStr;
    }

    /*********************************************************************** wjr */
    private void makeTable(String[][] tableData) {
        for (String[] tableData1 : tableData) {
            for (String item : tableData1) {
				////System.out.print(tableData[rdx][cdx] + " ");
                ////System.out.print(tableData[rdx][cdx] + " ");
            }
            ////System.out.println("");
        }

        this.tableData = tableData;

////System.out.println("RBP_mT: " + tableData);
        // read in header info and set up blank data for arbitrary number
        // of rows
        int hdrRows = 2;
        int bodRows = tableData.length - 2;

        int cntrow = hdrRows + bodRows;
        int cntcol = tableData[0].length;

        // find dimensions for data table
//		int[] columnWidths = getColumnWidths(cntcol);
        // Create table object
        jctable = new ToolTipsTable("RepBarPanel", new TFile("cfg", "reportstooltips.cfg"));
        ToolTipManager.sharedInstance().registerComponent(jctable);
        jctable.setLabels(new String[]{"barloc", "bartype", "barheight", "barwidth", "barpor"});

        // Create a vector data source to contain our data
        dataSource = new JCEditableVectorDataSource();

        jctable.setColumnLabelDisplay(false);
        jctable.setRowLabelDisplay(false);
        jctable.setDataSource(dataSource);

        dataSource.setNumRows(cntrow);
        dataSource.setNumColumns(cntcol);

        dataSource.setCells(tableData);

        jctable.setDoubleBuffered(true);
        jctable.setAutoScroll(JCTableEnum.AUTO_SCROLL_NONE);

        jctable.setPreferredSize(new Dimension(600, 160));

        JCCellStyle cs = new JCCellStyle();
        cs.setBackground(new Color(255, 255, 210));
//		cs.setForeground(Color.black);
//		cs.setHorizontalAlignment(JCTableEnum.CENTER);
//		cs.setClipHints(JCTableEnum.SHOW_NONE);
//		cs.setCellBorderSides(JCTableEnum.BORDERSIDE_ALL);
        cs.setEditable(false);
        cs.setTraversable(false);
        jctable.setCellStyle(new JCCellRange(0, 0, cntrow, 0), cs);

        // format barrier types
        cs = new JCCellStyle();
//		cs.setBackground(new Color(255,255,210));
        cs.setEditable(false);
        cs.setTraversable(false);
        jctable.setCellStyle(new JCCellRange(1, 1, cntrow, 1), cs);

        // format numeric values
        cs = new JCCellStyle();
//		cs.setBackground(new Color(255,255,210));
//		cs.setForeground(Color.black);
        cs.setHorizontalAlignment(JCTableEnum.RIGHT);
//		cs.setClipHints(JCTableEnum.SHOW_NONE);
//		cs.setCellBorderSides(JCTableEnum.BORDERSIDE_ALL);
        cs.setEditable(false);
        cs.setTraversable(false);
        jctable.setCellStyle(new JCCellRange(1, 2, cntrow, 4), cs);

        formatHeader();

//		formatCells(jctable, hdrRows, cntrow, cntcol);
        setLayout(new java.awt.GridLayout());

        jctable.setPixelWidth(0, 70);
        jctable.setPixelWidth(1, 345);
        jctable.setPixelWidth(2, 65);
        jctable.setPixelWidth(3, 65);
        jctable.setPixelWidth(4, 65);

        add(jctable);

    }

    /*********************************************************************** wjr */
    private void formatHeader() {
        JCCellRange spanrange = null;
        try {
            // span over side
            spanrange = new JCCellRange(0, 0, 1, 0);
            jctable.addSpannedRange(spanrange);
            // span for 'Barrier Type'
            spanrange = new JCCellRange(0, 1, 1, 1);
            jctable.addSpannedRange(spanrange);
        } catch (java.lang.IllegalArgumentException e) {
            //System.err.println("ROP_mHS: overlapping spanning ranges " + spanrange);
        }
        JCCellStyle cs = new JCCellStyle();
        cs.setHorizontalAlignment(JCTableEnum.CENTER);
        cs.setEditable(false);
        cs.setTraversable(false);
        jctable.setCellStyle(new JCCellRange(0, 0, 1, 4), cs);
    }

    /*********************************************************************** wjr
     * @param e */
//	Vector barVec = new Vector();
    @Override
    public void propertyChange(PropertyChangeEvent e) {
////System.out.println("pC: " + e.getPropertyName());
        if (e.getPropertyName().startsWith(RunFileData.Barrier)) {
            String side = e.getPropertyName();
            ////System.out.println("RBP_pC Value of side :"+ side);
            side = side.substring(side.length() - 1);
            //System.out.println("RBP_pC Value of side BEFORE :"+ side);
            if (side.equals("W")) {
                side = "West";
            }
            if (side.equals("S")) {
                side = "South";
            }
            if (side.equals("N")) {
                side = "North";
            }
            if (side.equals("E")) {
                side = "East";
            }
            //System.out.println("RBP_pC Value of side AFTER :"+ side);
//			barVec.add(new String(e.getPropertyName() + "|" + (String) e.getNewValue()));
            StringTokenizer st = new StringTokenizer((String) e.getNewValue(), "|");
            ////System.out.println("pC: " + e.getPropertyName() + " " + st.countTokens() + " " + (String) e.getNewValue());
            if (st.countTokens() != 4) {
                return;
            }
            for (int idx = 2; idx < tableData.length; idx++) {
                String val = (String) dataSource.getTableDataItem(idx, 0);
                /* if (val == "W"){val = "West";}
                 if (val == "S"){val = "South";}
                 if (val=="N"){val = "North";}
                 if (val == "E"){val = "East";}
                 //System.out.println("RBP_pC Value of val is :"+ val);*/
                if (val.trim().length() == 0) {
                    String type = st.nextToken().trim();
                    if (type.equals("none")) {
                        break;
                    }
                    dataSource.setTableDataItem(side, idx, 0);
                    tableData[idx][0] = (String) dataSource.getTableDataItem(idx, 0);
                    dataSource.setTableDataItem(type, idx, 1);
                    tableData[idx][1] = (String) dataSource.getTableDataItem(idx, 1);
                    dataSource.setTableDataItem((st.nextToken().trim()), idx, 2);
                    tableData[idx][2] = (String) dataSource.getTableDataItem(idx, 2);
                    dataSource.setTableDataItem((st.nextToken().trim()), idx, 3);
                    tableData[idx][3] = (String) dataSource.getTableDataItem(idx, 3);
                    dataSource.setTableDataItem((st.nextToken().trim()), idx, 4);
                    tableData[idx][4] = (String) dataSource.getTableDataItem(idx, 4);
                    switch (side) {
                        case "North":
                            changes.firePropertyChange(DrawField.ShowN, null, " ");
                            hasNorth = true;
                            break;
                        case "South":
                            changes.firePropertyChange(DrawField.ShowS, null, " ");
                            hasSouth = true;
                            break;
                        case "West":
                            changes.firePropertyChange(DrawField.ShowW, null, " ");
                            hasWest = true;
                            break;
                        case "East":
                            changes.firePropertyChange(DrawField.ShowE, null, " ");
                            hasEast = true;
                            break;
                    }
                    break;
                }
            }

        } else if (e.getPropertyName().equals(usda.weru.util.ConfigData.Units)) {
            if (measurementUnits.equals((String) e.getNewValue())) {
                return;
            }
            measurementUnits = (String) e.getNewValue();
            if (measurementUnits.equals(Util.USUnits)) {
                dataSource.setTableDataItem("ft", 1, 2);
                dataSource.setTableDataItem("ft", 1, 3);
            }
            @SuppressWarnings("unchecked")
            Vector<Vector<String>> cells = (Vector<Vector<String>>) dataSource.getCells();
            for (int rdx = 2; rdx < tableData.length - (4 - getBarrierCount()); rdx++) {
                Vector<String> cello = cells.elementAt(rdx);
                for (int cdx = 2; cdx < 5; cdx++) {
                    String temp = cello.elementAt(cdx);
                    temp = temp.trim();
                    if (temp.length() == 0) {
                        continue;
                    }
                    if (cdx == 4) {
                        temp = Util.convertMetersToFeetAndFormat(temp, Util.SIUnits, 2);
                    } else {
                        temp = Util.convertMetersToFeetAndFormat(temp, measurementUnits, 1);
                    }
                    dataSource.setTableDataItem(temp, rdx, cdx);
                    tableData[rdx][cdx] = temp;
                }
            }
            /*		} else if (e.getPropertyName().equals(RunFileData.FieldId)) {
             JTF_FieldID.setText((String) e.getNewValue());
             } else if (e.getPropertyName().equals(RunFileData.FarmId)) {
             JTF_FarmID.setText((String) e.getNewValue());
             } else if (e.getPropertyName().equals(RunFileData.TractId)) {
             JTF_TractID.setText((String) e.getNewValue());
             } else if (e.getPropertyName().equals(RunFileData.SoilFile)) {
             JTF_Soil.setText(new File((String) e.getNewValue()).getName());
             } else if (e.getPropertyName().equals(RunFileData.ManageFile)) {
             JTF_Management.setText(new File((String) e.getNewValue()).getName());*/
        }
    }

    /*======== End of property change handlers / Start of property change support */
    private final PropertyChangeSupport changes = new PropertyChangeSupport(this);

    /**
     *
     * @param l
     */
    @Override
    public void addPropertyChangeListener(PropertyChangeListener l) {
        changes.addPropertyChangeListener(l);
    }

    /**
     *
     * @param l
     */
    @Override
    public void removePropertyChangeListener(PropertyChangeListener l) {
        changes.removePropertyChangeListener(l);
    }

    /**
     *
     * @return
     */
    public int getTabelPixelHeight() {
        JCTable table = this.jctable;
        int height = 0;
        for (int i = 0; i <= table.getNumRows(); i++) {
            height = height + table.getRowPixelHeight(i);
        }
        return height;
    }

    /**
     *
     * @return
     */
    public int getBarrierCount() {
        int count = 0;
        if (hasNorth) {
            count++;
        }
        if (hasSouth) {
            count++;
        }
        if (hasEast) {
            count++;
        }
        if (hasWest) {
            count++;
        }
        return count;
    }

    /**
     *
     */
    public void removeExtraRows() {
        int count = getBarrierCount();
        if (count < 4) {
            dataSource.deleteRows(2 + count, 4 - count);
        }
    }

}
