package com.steering.comm.file;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.net.ftp.FTPFile;

import com.steering.comm.tools.StringTool;

import CoreFS.SA01.CoreIComponent;
import CoreFS.SA06.CoreReturnObject;

/**
 * FTP文件处理类
 * @author siy 2015-03-12
 * @version v1.0
 */
public class FtpStorage extends CoreIComponent implements IFtpStorage {

    public CoreReturnObject upload(ArrayList<HashMap<Object, Object>> files) {
        CoreReturnObject cro = new CoreReturnObject();

        if (files == null) {
            cro.setV_errMsg("上传文件不能为空！");
            return cro;
        }

        CoreFTPClient ftp = CoreFTPClient.newInstance();
        ArrayList<FileBean> list = convert(files);
        try {
            ftp.open();
            int upCount = 0;
            try {
                for (int i = 0; i < list.size(); i++) {
                    ftp.upload(list.get(i).getFile(),
                            list.get(i).getFileName(), list.get(i)
                                    .getPathName());
                    upCount++;
                }
            }
            catch (Exception ex) {
                try {
                    for (int i = 0; i < upCount; i++) {
                        ftp.deleteFile(list.get(i).getPathName() + "/"
                                + list.get(i).getFileName());
                    }
                }
                catch (Exception ex1) {

                }
                cro.setV_errCode(-1);
                cro.setV_errMsg("上传文件失败，请稍后重试！");
            }
        }
        catch (Exception ex) {

        }
        finally {
            if (ftp.isConnected()) {
                try {
                    ftp.close();
                }
                catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        return cro;
    }

    public CoreReturnObject download(String pathname) {
        CoreReturnObject cro = new CoreReturnObject();

        if (StringTool.isNullOrEmpty(pathname)) {
            cro.setV_errMsg("下载路径不能为空！");
            return cro;
        }

        List<FileBean> result = new ArrayList<FileBean>();
        CoreFTPClient ftp = CoreFTPClient.newInstance();
        try {
            ftp.open();
            String path = "";
            FTPFile[] files = ftp.listFiles(pathname);
            if (files != null && files.length > 0) {
                if (ftp.isPath(pathname)) {
                    path = pathname;
                }
                else {
                    String[] args = pathname.split("/");
                    if (args.length > 1) {
                        path = pathname.substring(0, pathname.length()
                                - (args[args.length - 1].length() + 1));
                    }
                }

                for (FTPFile ff : files) {
                    if (ff.isFile()) {
                        FileBean bean = new FileBean();
                        byte[] bFile = ftp.Download(path + "/" + ff.getName());
                        bean.setFile(bFile);
                        bean.setFileName(new String(ff.getName().getBytes(
                                ftp.getEncoding()), "gb2312"));
                        bean.setPathName(path);
                        System.out.println(bean.getFileName() + "   "
                                + bean.getFile().length);
                        result.add(bean);
                    }
                }
            }
        }
        catch (Exception ex) {

        }
        finally {
            if (ftp.isConnected()) {
                try {
                    ftp.close();
                }
                catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        cro.setResult(result);
        return cro;
    }

    public CoreReturnObject delete(String pathname) {
        CoreReturnObject cro = new CoreReturnObject();

        if (StringTool.isNullOrEmpty(pathname)) {
            cro.setV_errMsg("路径不能为空！");
            return cro;
        }

        CoreFTPClient ftp = CoreFTPClient.newInstance();
        try {
            ftp.open();
            if (ftp.isPath(pathname)) {
                if (!ftp.deletePath(pathname)) {
                    cro.setV_errCode(-1);
                    cro.setV_errMsg("删除失败！");
                }
            }
            else {
                String path = "";
                String[] args = pathname.split("/");
                if (args.length > 1) {
                    path = pathname.substring(0, pathname.length()
                            - (args[args.length - 1].length() + 1));
                }
                if(args.length > 0){
                    path += "/"+new String(args[args.length-1].getBytes(),ftp.getControlEncoding());
                }
                if(!StringTool.isNullOrEmpty(path)){
                    ftp.deleteFile(path);
                }
            }
        }
        catch (Exception ex) {

        }
        finally {
            if (ftp.isConnected()) {
                try {
                    ftp.close();
                }
                catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

        return cro;
    }

    private static ArrayList<FileBean> convert(
            ArrayList<HashMap<Object, Object>> list) {
        ArrayList<FileBean> result = null;
        if (list != null) {
            result = new ArrayList<FileBean>();
            for (HashMap<Object, Object> ht : list) {
                FileBean bean = hashMapToBean(ht);
                result.add(bean);
            }
        }

        return result;
    }

    private static FileBean hashMapToBean(HashMap<Object, Object> ht) {
        FileBean bean = null;

        if (ht != null && ht.size() > 0) {
            bean = new FileBean();
            if (ht.keySet().contains("file")) {
                bean.setFile((byte[]) ht.get("file"));
            }
            if (ht.keySet().contains("fileName")) {
                bean.setFileName(ht.get("fileName").toString());
            }
            if (ht.keySet().contains("pathName")) {
                bean.setPathName(ht.get("pathName").toString());
            }
        }

        return bean;
    }
}
