/*
 * Copyright (C) 2005 - 2011 Jaspersoft Corporation. All rights reserved.
 * http://www.jaspersoft.com.
 *
 * Unless you have purchased  a commercial license agreement from Jaspersoft,
 * the following license terms  apply:
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License  as
 * published by the Free Software Foundation, either version 3 of  the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero  General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public  License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.jaspersoft.jasperserver.irplugin.gui.dndobjects;
import com.jaspersoft.jasperserver.api.metadata.xml.domain.impl.ResourceDescriptor;
import com.jaspersoft.jasperserver.irplugin.IRPlugin;
import com.jaspersoft.jasperserver.irplugin.RepositoryFile;
import com.jaspersoft.jasperserver.irplugin.RepositoryFolder;
import com.jaspersoft.jasperserver.irplugin.RepositoryReportUnit;
import it.businesslogic.ireport.HyperLinkableReportElement;
import it.businesslogic.ireport.ImageReportElement;
import it.businesslogic.ireport.JRLinkParameter;
import it.businesslogic.ireport.JRParameter;
import it.businesslogic.ireport.Report;
import it.businesslogic.ireport.ReportElement;
import it.businesslogic.ireport.SubReportElement;
import it.businesslogic.ireport.TextFieldReportElement;
import it.businesslogic.ireport.gui.ElementPropertiesDialog;
import it.businesslogic.ireport.gui.FieldPatternDialog;
import it.businesslogic.ireport.gui.MainFrame;
import it.businesslogic.ireport.gui.event.ReportElementChangedEvent;
import it.businesslogic.ireport.gui.library.*;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Point;
import java.awt.image.ImageObserver;
import java.awt.image.ImageProducer;
import java.util.List;
import javax.swing.JOptionPane;
/**
 *
 * @author  Administrator
 */
public class FileObject extends AbstractLibraryObject {
           
    private RepositoryFolder repositoryFile = null;
    
    /** Creates a new instance of PageNumberObject */
    public FileObject(RepositoryFolder repositoryFile) {
        this.setRepositoryFile(repositoryFile);
    }
    
    public String getName()
    {
        return "" + repositoryFile;
    }

    public void drop(java.awt.dnd.DropTargetDropEvent dtde) {
        
            try {

            ResourceDescriptor rdMain = getRepositoryFile().getDescriptor();
            ResourceDescriptor rd = rdMain;
            if (rdMain.getIsReference())
            {
                // Load referenced...
                ResourceDescriptor rd2 = new ResourceDescriptor();
                rd2.setUriString( rdMain.getReferenceUri() );
                rd = getRepositoryFile().getServer().getWSClient().get(rd2, null);
                if (rd == null) rd = rdMain;
            }
            
            if (rd.getWsType().equals( ResourceDescriptor.TYPE_IMAGE))
            {
                ImageReportElement ire = new ImageReportElement(0,0,10,10);
                ire.setImageClass("java.lang.String");
                if (rd.getParentFolder() != null &&
                    rd.getParentFolder().endsWith("_files"))
                {
                    // Assume it is a RU local resource....
                    ire.setImageExpression("\"repo:" +  rd.getName() + "\"");
                }
                else
                {
                    ire.setImageExpression("\"repo:"  + rd.getUriString() + "\"");
                }

                // Try to load this image...
                int w=200,h=100;
                try {
                    RepositoryFile rf = new RepositoryFile(getRepositoryFile().getServer(), rd);
                    String fileName = rf.getFile();
                    if (fileName != null)
                    {
                        javax.swing.ImageIcon img = new javax.swing.ImageIcon(fileName);
                        ire.setImg(img.getImage());
                        w = img.getIconWidth();
                        h = img.getIconHeight();
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                getReportFrame().dropReportElement( dtde.getLocation(), ire, w, h);
            }
            else if (rd.getWsType().equals( ResourceDescriptor.TYPE_JRXML))
            {
                Report report = getReport();
                if (rd.isMainReport()) return;
                SubReportElement sre = new SubReportElement(0,0,10,10);
                sre.setSubreportExpressionClass("java.lang.String");
                if (rd.getParentFolder() != null &&
                    rd.getParentFolder().endsWith("_files"))
                {
                    // Assume it is a RU local resource....
                    sre.setSubreportExpression("\"repo:" +  rd.getName() + "\"");
                }
                else
                {
                    sre.setSubreportExpression("\"repo:"  + rd.getUriString() + "\"");
                }
                sre.setConnectionExpression("$P{REPORT_CONNECTION}");
                sre.setUseConnection(true);
                
                Point p = dtde.getLocation();
                p.x = getReportFrame().getZoomedDim( report.getLeftMargin()) - getReportFrame().getHScroll()+10;
                getReportFrame().dropReportElement( p, sre, 
                        report.getWidth() - report.getLeftMargin() - report.getRightMargin(), 100);
            }
            else if (rd.getWsType().equals( ResourceDescriptor.TYPE_INPUT_CONTROL))
            {
                Report report = getReportFrame().getReport();
                
                if (report == null) return;
                java.util.Vector v = report.getParameters(); 
                
                boolean found = false;
                for (int i=0; i<v.size(); ++i)
                {
                    it.businesslogic.ireport.JRParameter parameter = (it.businesslogic.ireport.JRParameter)v.get(i);
                    if (parameter.getName().equals( rd.getName() )) 
                    {
                        it.businesslogic.ireport.gui.JRParameterDialog jrpd = new it.businesslogic.ireport.gui.JRParameterDialog(MainFrame.getMainInstance(), true);
                        jrpd.setParameter( parameter );
                        jrpd.setVisible(true);
                        
                        
                        if (jrpd.getDialogResult() == javax.swing.JOptionPane.OK_OPTION)
                        {
                            report.getKeywordLookup().removeKeyword(
                                    "$P{" + parameter.getName() + "}");
                            parameter.setName(jrpd.getParameter().getName());
                            report.getKeywordLookup().addKeyword(
                                    "$P{" + parameter.getName() + "}");
                            parameter.setClassType(jrpd.getParameter().getClassType());
                            parameter.setDescription(jrpd.getParameter().getDescription());
                            parameter.setDefaultValueExpression(jrpd.getParameter().getDefaultValueExpression());
                            parameter.setIsForPrompting(jrpd.getParameter().isIsForPrompting());

                            report.fireSubDatasetObjectChangedListenerSubDatasetObjectChanged(new it.businesslogic.ireport.gui.event.SubDatasetObjectChangedEvent(report, 
                                                                                                       it.businesslogic.ireport.gui.event.SubDatasetObjectChangedEvent.PARAMETER, 
                                                                                                       it.businesslogic.ireport.gui.event.SubDatasetObjectChangedEvent.PARAMETER, 
                                                                                                       parameter, 
                                                                                                       parameter));
                        }  
                        found = true;
                        break;
                    }
                }
                
                if (!found)
                {
                    it.businesslogic.ireport.JRParameter newParam = new it.businesslogic.ireport.JRParameter( rd.getName(), "java.lang.String");
                    it.businesslogic.ireport.gui.JRParameterDialog jrpd = new it.businesslogic.ireport.gui.JRParameterDialog(MainFrame.getMainInstance(), true);
                        newParam.setIsForPrompting(true);
                        jrpd.setParameter( newParam );
                        jrpd.setSubDataset( report );
                        jrpd.setVisible(true);
                        
                        
                        if (jrpd.getDialogResult() == javax.swing.JOptionPane.OK_OPTION)
                        {
                            JRParameter parameter = jrpd.getParameter();
                            report.addParameter(parameter);
                        }  
                }
                
                
            }
            else if (rd.getWsType().equals( ResourceDescriptor.TYPE_REPORTUNIT))
            {
                // Find the object on that location....
                //
                ReportElement re = getReportFrame().getElementAt(dtde.getLocation());
                if (re != null && re instanceof HyperLinkableReportElement)
                {
                    HyperLinkableReportElement hre = (HyperLinkableReportElement)re;
                    hre.setHyperlinkType("ReportExecution");
                    
                    List linkParameters = new java.util.ArrayList();
                    linkParameters.add(new JRLinkParameter("_report","\"" + rd.getUriString() + "\"" ));
                    
                    List listChildren = rd.getChildren();
                    if (repositoryFile instanceof RepositoryReportUnit)
                    {
                        RepositoryReportUnit reportUnit = (RepositoryReportUnit)repositoryFile;
                        if (!reportUnit.isLoaded() || rd.getChildren().size() == 0)
                        {
                            ResourceDescriptor descriptor = new ResourceDescriptor();
                            descriptor.setWsType( descriptor.TYPE_REPORTUNIT);
                            descriptor.setUriString(reportUnit.getDescriptor().getUriString());
                            
                            listChildren = reportUnit.getServer().getWSClient().list(descriptor);
                        }
                    }
                    
                    // Look for all the Input controls availables....
                    for (int i=0; i<listChildren.size(); ++i)
                    {
                        ResourceDescriptor childRd = (ResourceDescriptor)listChildren.get(i);
                        if (childRd.getWsType().equals( childRd.TYPE_INPUT_CONTROL ))
                        {
                            linkParameters.add(new JRLinkParameter(childRd.getName(),""));
                        }
                    }
                    
                    hre.setLinkParameters(linkParameters);
                    
                    getReportFrame().setSelectedElement(re);
                    MainFrame.getMainInstance().getElementPropertiesDialog().setVisible(true);
                    MainFrame.getMainInstance().getElementPropertiesDialog().gotoTab( ElementPropertiesDialog.HYPERLINK_TAB );
                }
                else
                {
                    JOptionPane.showMessageDialog(MainFrame.getMainInstance(),
                            IRPlugin.getString("messages.fileObject.notHyperlinkElement", "Please drag your Report Unit over an hyper linkable element like a text field, an image or a chart."));
                }
            }
            } catch (Exception ex)
            {
                ex.printStackTrace();
            }
    }
    
    public RepositoryFolder getRepositoryFile() {
        return repositoryFile;
    }

    public void setRepositoryFile(RepositoryFolder repositoryFile) {
        this.repositoryFile = repositoryFile;
    }
    
}
