/*
 * blanco Framework
 * Copyright (C) 2004-2006 IGA Tosiki
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 */
package blanco.plugin.filemanager.views.item;

import java.util.ArrayList;

import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemException;
import org.apache.commons.vfs.FileSystemManager;
import org.apache.commons.vfs.VFS;
import org.apache.commons.vfs.cache.OnCallRefreshFileObject;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.Viewer;

public class BlancoFileManagerProtocolFtpItem implements
        IStructuredContentProvider {
    private FileObject[] fileRoots = null;

    private String fProtocol = null;

    public BlancoFileManagerProtocolFtpItem(final String argProtocol) {
        fProtocol = argProtocol;
    }

    public String toString() {
        return fProtocol;
    }

    public Object[] getElements(final Object inputElement) {
        // fProtocol

        // 現在は file:// のみ対応。
        if (fileRoots == null) {
            // ここでルートを作成します。
            try {
                final ArrayList listWrk = new ArrayList();
                // ※例外的に java.io.Fileを利用しています。

                final FileSystemManager manager = VFS.getManager();

                addFtpChildItem(
                        "ftp://anonymous:blancoFileManager@ftp.iij.ad.jp/",
                        manager, listWrk);
                addFtpChildItem(
                        "ftp://anonymous:blancoFileManager@sh.wide.ad.jp/",
                        manager, listWrk);

                fileRoots = (FileObject[]) listWrk
                        .toArray(new FileObject[listWrk.size()]);

            } catch (FileSystemException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            } catch (Error e) {
                e.printStackTrace();
            }
        }

        return fileRoots;
    }

    public void dispose() {
    }

    public void inputChanged(final Viewer viewer, final Object oldInput,
            final Object newInput) {
    }

    private void addFtpChildItem(final String url,
            final FileSystemManager manager, final ArrayList listWrk) {
        try {
            listWrk.add(new OnCallRefreshFileObject(manager.resolveFile(url)));
        } catch (FileSystemException ex) {
            // 2006.12.11 IGA Tosiki: ftpの場合には、「java.net.ConnectException:
            // Connection timed out」をcauseとする FileSystemException などが ここで発生します。
            ex.printStackTrace();
        }
    }
}
