package iDSS.beans2;


import java.awt.image.*;
import java.util.*;
import java.io.*;
import java.net.*;
import java.beans.*;
import java.awt.*;




import iDSS.utils.*;
import iDSS.disp.*;
import iDSS.grids.*;
import iDSS.utils.*;
import iDSS.gridDisp.*;
import iDSS.beans.*;



public class GridManagerJBean {

    private Hashtable gridsHashtable;

    private String currentFileName,currentName;
    private File currentFile;
    private Grid currentGrid;
    private Vector currentRow;

    private PropertyChangeSupport pcs;
    private String title;
    private int gridType;
    private String serverGridTable;
    private String hashCode;
    private String ejbName;




    public GridManagerJBean() {


        gridType = IDSSAppConstants.gridTypeDEM;
        serverGridTable = IDSSAppConstants.gridsTableName;
        this.hashCode = IDSSAppConstants.demGridName;
        title = IDSSAppConstants.modelSetupDemRemote;
        ejbName = IDSSAppConstants.gridsBean;

        if(IDSSAppConstants.debug) {
            System.out.println("GridManagerJBean.GridManagerJBean(), serverGridTable : " + serverGridTable);
        } //if(IDSSAppConstants.debug)

        pcs = new PropertyChangeSupport(this);

        gridsHashtable = new Hashtable();

    } //public GridManagerJBean();





    public Hashtable getGrids() {

        return gridsHashtable;

    } //public Hashtable getGrids()






    public void setCurrentFileName(String fileName) {

        if(fileName != null) {

            currentFileName = fileName;
            currentFile = new File(currentFileName);
            currentGrid = (Grid)gridsHashtable.get(currentFileName);
            currentName = (String) currentGrid.getName();
            currentRow = new Vector();
            currentRow.add(currentName);
            currentRow.add(currentFileName);

        } //if(fileName != null)

        else {

            currentFileName = null;
            currentFile = null;
            currentGrid = null;
            currentName = null;
            currentRow = null;

        } //else

    } //public void setSelectedRow(String fileName)





    public String getCurrentFileName() {

        return currentFileName;

    } //public String getCurrentFileName()





    public void addToGrids(Grid grid) {


        if(grid!=null) {

            if(gridsHashtable.containsKey(grid.getFileName())) {

                currentFileName = grid.getFileName();
                removeFromGrids();

            }//if(gridsHashtable.containsKey(grid.getFileName()))

            gridsHashtable.put(grid.getFileName(),grid);

            Vector gridNames = new Vector();
            gridNames.add(grid.getName());
            gridNames.add(grid.getFileName());
            pcs.firePropertyChange(IDSSAppConstants.GridManagerAddToGrids,null,gridNames);

        } //if(grid!=null)

        //saveServerButton.setEnabled(false);

    } //public void addToDataSet(aDataSet)





    public void removeFromGrids() {

        gridsHashtable.remove(currentFileName);

        Vector row = new Vector();
        row.add(currentGrid.getName());
        row.add(currentGrid.getFileName());

        pcs.firePropertyChange(IDSSAppConstants.GridManagerRemoveFromGrids,null,row);

    } //public void removeFromGrids()






    public void pickGrid() {

        File inFile = FileNameDialog.getInputFileName(title,null,null);

        if (inFile != null) {

            Grid aGrid = new Grid(inFile.toString(),gridType,0,inFile);
            if(!aGrid.isRead())
                aGrid.read();

            addToGrids(aGrid);

        }//if (inFile != null)


    } //public void pickGrid()




    public void pickGrid(File inFile) {


        if (inFile != null) {

            Grid aGrid = new Grid(inFile.toString(),gridType,0,inFile);
            if(!aGrid.isRead())
                aGrid.read();

            addToGrids(aGrid);

        }//if (inFile != null)



    } //public void pickGrid(File inFile)






    public String pickGrid(String inFileName) {

        String s = "Failed to read from " + inFileName;

        try {

            if(inFileName != null) {

                File inFile = new File(inFileName);

                if (inFile != null) {

                    Grid aGrid = new Grid(inFile.toString(),gridType,0,inFile);
                    if(!aGrid.isRead())
                        aGrid.read();

                    addToGrids(aGrid);

                    s = "Read successfully from " + inFileName;

                }//if (inFile != null)

            } //if(inFileName != null)

        } //try

        catch(NullPointerException e) {

            String message = "GridManagerJBean.pickGrid(String), fileName : " + inFileName + ", " + e.toString();
            Vector messageVector = new Vector();
            messageVector.add("Can't read grid from file");
            messageVector.add(message);
            messageVector.add(new Integer(IDSSAppConstants.errorMessage));

            pcs.firePropertyChange(IDSSAppConstants.showMessage,null,messageVector);

        } //catch(NullPointerException e)

        return s;

    } //public String pickGrid(File inFile)







/** This method will work only if the URL is published by a web server


    public String pickGrid(String fileName) {

        String message = "Failed to read from file";

        try {

            if(fileName != null) {

                System.out.println("fileName : " + fileName);

                File inFile = new File(fileName);

                URL url = null;

                if(inFile != null) {

                    System.out.println("inFile : " + inFile.toString());

                    url = inFile.toURL();
                    System.out.println("url : " + url.toString());

                }

                if (url != null) {

                    Grid aGrid = new Grid(inFile.toString(),gridType,0,inFile);
                    if(!aGrid.isRead())
                        aGrid.read(url);

                    addToGrids(aGrid);

                    message = "Reading complete";

                }//if (inFile != null)


            } //if(fileName != null)

        } //try

        catch(Exception e) {

            System.out.println("GridManagerJBean.pickGrid(String fileName), " + e.toString());
            message = "Failed to read from file";

        } //catch(Exception e)


        return message;

    } //public String pickGrid(String fileName)


**/







    public void describe() {

        currentGrid = (Grid) gridsHashtable.get(currentFileName);

        if (!currentGrid.isRead()) {
            currentGrid.read();
        }


        Vector gridDesc = currentGrid.showdescription();
        pcs.firePropertyChange(IDSSAppConstants.GridManagerGridDesc,null,gridDesc);


    } //public void describe()












    public void saveToServer() {


        GridsJBean gridsJBean = new GridsJBean();
        gridsJBean.setEjbName(ejbName,serverGridTable);

        currentGrid = (Grid) gridsHashtable.get(currentFileName);

        if(currentGrid != null) {

            gridsJBean.saveOnServer(currentGrid,IDSSAppConstants.ip,currentFileName);

        } //if(currentGrid != null)


    } //public void saveToServer()





    public void pickFromServer() {

        GridsJBean gridsJBean = new GridsJBean();
        gridsJBean.setEjbName(ejbName,serverGridTable);

        Collection grids = gridsJBean.findAll();

        if (grids != null) {

            Iterator i = grids.iterator();
            while(i.hasNext()) {

                Grid g = (Grid)i.next();
                g.setType(gridType);
                addToGrids(g);

            } //while(i.hasNext())

        } //if (grids != null)



    } //public void pickFromServer()








    public void selectGrid() {

        currentGrid = (Grid) gridsHashtable.get(currentFileName);

        if(currentGrid != null) {
            System.out.println("GridManagerJBean.selectGrid(), currentGrid not null");
            System.out.println("currentGrid.getName() : " + currentGrid.getName());
            Vector v = new Vector();
            v.add(hashCode);
            v.add(currentGrid);
            pcs.firePropertyChange(IDSSAppConstants.addGridToModel,null,v);
        } //if(currentGrid != null)

        else {
            if(IDSSAppConstants.debug) {

                DebugWriter.writeDebug("GridManagerJBean.selectGrid(), currentGrid = null");
                System.out.println("GridManagerJBean.selectGrid(), currentGrid = null");

            } //if(IDSSAppConstants.debug)

        }//else


    } //public void selectGrid()





    public BufferedImage getImage() {

        BufferedImage bi = null;
        currentGrid = (Grid) gridsHashtable.get(currentFileName);

        if(currentGrid != null) {

            if (!currentGrid.isRead()) {
                currentGrid.read();
            }

            SurfaceColor sc = new SurfaceColor(currentGrid.getName(),currentGrid.getZMin(),
                                        currentGrid.getZMax(),SurfaceColor.DEM);
            bi = currentGrid.getImage(sc);

        } //if(currentGrid != null)


        return bi;


    } //public BufferedImage getImage()










    public void drawGrid() {

        if(IDSSAppConstants.debug)
            System.out.println("GridManagerJBean.drawGrid(), file : " + currentFileName);

        currentGrid = (Grid) gridsHashtable.get(currentFileName);

        if (!currentGrid.isRead()) {
            currentGrid.read();
        }


        SurfaceColor sc = new SurfaceColor(currentGrid.getName(),currentGrid.getZMin(),
                                        currentGrid.getZMax(),SurfaceColor.DEM);

        GridDisplay gridDisplay = new GridDisplay(currentGrid.getName());

        currentGrid.draw(gridDisplay,sc);

        pcs.firePropertyChange(IDSSAppConstants.GridManagerGridDisp,null,gridDisplay);

        ImageDisplay legendFrame = new ImageDisplay(currentGrid.getName()+
                                        ":Legend",sc.getLegendWidth(),
                                        sc.getLegendHeight());

        pcs.firePropertyChange(IDSSAppConstants.GridManagerImgDisp,null,legendFrame);
        sc.drawLegend(legendFrame);



    } //public void drawGrid()





    private Vector makeImageAndLegend() {


        currentGrid = (Grid) gridsHashtable.get(currentFileName);
        Vector v = new Vector();

        if(currentGrid != null) {

            if (!currentGrid.isRead()) {
                currentGrid.read();
            }

            SurfaceColor sc = new SurfaceColor(currentGrid.getName(),currentGrid.getZMin(),
                                        currentGrid.getZMax(),SurfaceColor.DEM);
            BufferedImage bi = currentGrid.getImage(sc);


            ImageDisplay legendFrame = new ImageDisplay(currentGrid.getName()+
                                        ":Legend",sc.getLegendWidth(),
                                        sc.getLegendHeight());

            BufferedImage legendBi = sc.getImage(legendFrame);


            v.add(bi);
            v.add(legendBi);

        } //if(currentGrid != null)

        return v;

    } //private Vector makeImageAndLegend()








    public Vector drawGridImg() {


        Vector images = makeImageAndLegend();
        Vector v = new Vector();


        if(images!=null) {

            if(images.size() > 0) {

                BufferedImage gridImg = (BufferedImage)images.elementAt(0);
                gridImg = ImageRW.scaleImage(gridImg);

                Vector imgVector = ImageRW.writeImgFile(gridImg);
                imgVector.add(currentGrid.getName());

                v.add(imgVector);

            } //if(images.size() > 0)

            if(images.size() > 1) {

                BufferedImage legendImg = (BufferedImage)images.elementAt(1);

                Vector imgVector = ImageRW.writeImgFile(legendImg);
                imgVector.add(currentGrid.getName() + ":Legend");

                v.add(imgVector);

            } //if(images.size() > 1)


        } //if(images!=null)

        return v;




/**
        if(currentGrid != null) {

            if (!currentGrid.isRead()) {
                currentGrid.read();
            }

            SurfaceColor sc = new SurfaceColor(currentGrid.getName(),currentGrid.getZMin(),
                                        currentGrid.getZMax(),SurfaceColor.DEM);
            BufferedImage bi = currentGrid.getImage(sc);
            Vector gridImg = ImageRW.writeImgFile(bi);
            gridImg.add(currentGrid.getName());


            ImageDisplay legendFrame = new ImageDisplay(currentGrid.getName()+
                                        ":Legend",sc.getLegendWidth(),
                                        sc.getLegendHeight());

            BufferedImage legendBi = sc.getImage(legendFrame);
            Vector legendImg = ImageRW.writeImgFile(legendBi);
            legendImg.add(currentGrid.getName() + ":Legend");


            v.add(gridImg);
            v.add(legendImg);

        } //if(currentGrid != null)
**/


    } //public Vector drawGridImg()







    public BufferedImage getImageAndLegend() {

        int gridImgVGap = 50;

        BufferedImage bi = null;
        Vector images = makeImageAndLegend();

        BufferedImage gridImg = null;
        BufferedImage legendImg = null;

        if(images!=null) {

            int width = 0;
            int height = 0;

            if(images.size() > 0) {

                gridImg = (BufferedImage)images.elementAt(0);
                gridImg = ImageRW.scaleImage(gridImg);

                width = width + gridImg.getWidth();
                height = Math.max(height,gridImg.getHeight()+gridImgVGap);

            } //if(images.size() > 0)

            if(images.size() > 1) {

                legendImg = (BufferedImage)images.elementAt(1);

                width = width + legendImg.getWidth() + 5;
                height = Math.max(height,legendImg.getHeight());

            } //if(images.size() > 1)

            bi = new BufferedImage (width,height,BufferedImage.TYPE_INT_RGB);

            Graphics g = bi.getGraphics();

            g.setColor(Color.white);
            g.fillRect(0,0,width,height); 
            g.setColor(Color.black); 

            g.drawImage(gridImg,0,gridImgVGap,null);
            g.drawImage(legendImg,gridImg.getWidth()+5,0,null);

        } //if(images!=null)

        return bi;

    } //public BufferedImage getImageAndLegend()









/**


    private Vector writeImgFile(BufferedImage bi) {

        BufferedImage bi2 = null;

        if ((bi.getWidth() < MINIMUM_IMAGE_SIZE) && (bi.getHeight() < MINIMUM_IMAGE_SIZE)) {

            int longSide = Math.max(bi.getWidth(),bi.getHeight());
            int ratio = MINIMUM_IMAGE_SIZE / longSide;

            bi2 = new BufferedImage (bi.getWidth()*ratio,bi.getHeight()*ratio,BufferedImage.TYPE_INT_RGB);
            Graphics g2 = bi2.getGraphics();
            g2.drawImage(bi,0,0,bi2.getWidth(),bi2.getHeight(),0,0,bi.getWidth(),bi.getHeight(),null);

        }

        else {
            bi2 = bi;
        }


        File tempDir = new File(IDSSAppConstants.tempDir);
        if(!tempDir.exists())
            tempDir.mkdirs();

        File tempOutFile = new File(tempDir,FileNameDialog.getTempFileName());
        tempOutFile.deleteOnExit();

        if(tempOutFile.exists())
            tempOutFile.delete();


        try {
            ImageIO.write(bi2, "png", tempOutFile);
        }

        catch(javax.imageio.IIOException ie) {

            System.out.println("GridViewColtrol.writeImgFiles(), " + ie.toString());

        } //catch(javax.imageio.IIOException ie)

        Vector v = new Vector();
        v.add(tempOutFile.toString());
        v.add(new Integer(bi2.getWidth()));
        v.add(new Integer(bi2.getHeight()));

        System.out.println("GridManagerJBean.writeImgFile(), with, height : " + bi2.getWidth() + "," + bi2.getHeight());

        return v;

    } //private Vector writeImgFile(BufferedImage bi)


**/





    public void addPropertyChangeListener(PropertyChangeListener l) {

        pcs.addPropertyChangeListener(l);

    } //public void addPropertyChangeListener(PropertyChangeListener l)



    public void removePropertyChangeListener(PropertyChangeListener l) {

        pcs.removePropertyChangeListener(l);

    } //public void removePropertyChangeListener(PropertyChangeListener l)






    public String toString() {

        return "GridManagerJBean";

    } //public String toString()


} //public class GridManagerJBean



