/*
 * 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;

import com.jaspersoft.jasperserver.api.metadata.xml.domain.impl.ResourceDescriptor;
import java.io.File;


/**
 *
 * @author gtoffoli
 */
public class RepositoryFile extends RepositoryFolder {

    private String localFileName = null;
    
    
    /** Creates a new instance of RepositoryFolder */
    public RepositoryFile(JServer server, ResourceDescriptor descriptor) {
        super( server, descriptor);
    }

    public String toString()
    {
        if (getDescriptor() != null)
        {
            return ""+getDescriptor().getLabel();
        }   
        return "???";
    }
    
    /**
     * This method return the file rapresented by this resource file.
     * The file is cached in a temporary directory for subsequent calls to this method.
     * Please note: the file is never removed... a delete of this file should be done
     * on plugin startup....
     * The method returns the cached file name.
     *
     */
    public String getFile() throws Exception
    {
        if (localFileName == null)
        {
            String localFile = IRPlugin.getMainInstance().createTmpFileName("img",null);
            try {
                //System.out.println("File saved here: " + localFile);
                getServer().getWSClient().get(getDescriptor(), new File(localFile));
            } catch (Exception ex)
            {
                ex.printStackTrace();
            }
            
            this.localFileName = localFile;
        }
        return localFileName;
    }
    
    /**
     * If localFileName exists, remove it and set localFileName to NULL.
     */
    public void resetFileCache()
    {
        if (localFileName != null)
        {
            File f = new File(localFileName);
            if (f.exists())
            {
                f.delete();
            }
        }
        
        localFileName = null;
    }

}
