package CoreFS.UpLoadManager;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Date;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.map.ListOrderedMap;

import CoreFS.SA01.CoreException;
import CoreFS.SA01.CoreIComponent;
import CoreFS.SA06.CoreReturnObject;
import CoreFS.Util.DateAndStringFormat;
import CoreFS.Util.StringUtils;

public class CoreUpLoad extends CoreIComponent {
    /*
     * 接收上传的文件
     */
    public CoreReturnObject ReceiveFile(UpLoadBean u) {
        CoreReturnObject cro = new CoreReturnObject();
        try {
            if (StringUtils.isFtp) {
                String path = StringUtils.mainPath + u.upLoadDir;// .substring(u.upLoadDir.indexOf("/",
                                                                 // 1));
                CoreFTPClient.Upload(u.getFileContent(), u.fileName, path);
            }
            else {
                String path = getPath();
                path = path + u.upLoadDir + "/" + u.fileName;
                upLoadFile(path, u.getFileContent());
            }
        }
        catch (Exception e) {
            // TODO: handle exception
            cro = cro.SetErrInfo("上传文件失败！" + e.getMessage());
        }
        return cro;
    }

    public CoreReturnObject downLoad(String path, String fileName) {
        CoreReturnObject cro = new CoreReturnObject();
        byte[] result = null;
        if (StringUtils.isFtp) {
            path = StringUtils.mainPath + path;
            path = path.replace("\\", "/");
            try {
                result = CoreFTPClient.Download(path, fileName);
                cro.setResult(result);
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                cro = cro.SetErrInfo("下载文件失败" + e.getMessage());
            }
        }
        else {
            path = getPath().replace("\\", "/") + path + "/";
            try {
                if (new File(path + fileName).isFile()) {
                    cro.setResult(CoreUtil.toByteArray(new FileInputStream(path
                            + fileName)));
                }
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                cro.SetErrInfo("下载文件失败" + e.getMessage());
            }
        }
        return cro;
    }

    /*
     * 读取更新目录
     */
    @SuppressWarnings("unchecked")
    public CoreReturnObject ReadFilesInfo() {
        CoreReturnObject cro = new CoreReturnObject();
        try {
            ArrayList directory = new ArrayList();
            if (StringUtils.isFtp) {
                CoreFTPClient.listAllRemoteFiles(StringUtils.mainPath,
                        directory);
            }
            else {
                String path = getPath();
                readUpLoadDirectory(path, "", directory);
            }
            UpLoadBean upload = new UpLoadBean();
            upload.upLoadDirectory = directory;
            cro.setResult(upload);
        }
        catch (Exception e) {
            cro = cro.SetErrInfo("读取文件信息失败！" + e.getMessage());
        }
        return cro;
    }

    /**
     * 读取filelist.xml
     * @param path
     * @return
     */
    public CoreReturnObject ReadFileXmlInfo(String path) {
        String content = "";
        CoreReturnObject cro = new CoreReturnObject();
        try {
            if (StringUtils.isFtp) {
                String rootpath = StringUtils.mainPath + path;
                byte[] fileByte = CoreFTPClient.Download(rootpath,
                        "filelist.xml");
                if (fileByte != null)
                    content = new String(fileByte);
            }
            else {
                String rootPath = getPath();
                path = rootPath + path + "/filelist.xml";
                File f = new File(path);
                if (f.exists()) {
                    content = readFiletoString(f);
                }
            }
            cro.setResult(content);
        }
        catch (Exception e) {
            cro = cro.SetErrInfo("读取配置信息失败！" + e.getMessage());
        }
        return cro;
    }

    /*
     * 保存filelist.xml
     */
    public CoreReturnObject WriteFileXmlInfo(String path, String Content) {
        CoreReturnObject cro = new CoreReturnObject();
        try {
            if (StringUtils.isFtp) {
                path = StringUtils.mainPath + File.separator + path;// .substring(path.indexOf("/",1));//+File.separator+"filelist.xml";
                byte[] filelist = Content.getBytes();
                CoreFTPClient.Upload(filelist, "filelist.xml", path);

            }
            else {
                String rootPath = getPath();
                path = rootPath + path + "/filelist.xml";
                WriteFile(path, Content);
            }
        }
        catch (Exception e) {
            cro.setV_errCode(-1);
            cro.setV_errMsg("写入配置信息失败！" + e.getMessage());
        }
        return cro;
    }

    /*
     * 创建目录
     */
    public CoreReturnObject CreateDirectory(String path) {
        CoreReturnObject cro = new CoreReturnObject();
        try {
            if (StringUtils.isFtp) {
                path = StringUtils.mainPath + path;// .substring(path.indexOf("/",1));
                boolean isSuc = CoreFTPClient.createFiles(path);
                cro.setResult(isSuc);
            }
            else {
                String rootPath = getPath();
                path = rootPath + path;
                boolean isSuc = CreateFiles(path);
                cro.setResult(isSuc);
            }
        }
        catch (Exception e) {
            cro = cro.SetErrInfo("创建目录失败！" + e.getMessage());
        }
        return cro;
    }

    /*
     * 删除目录
     */
    public CoreReturnObject DeleteFiles(String path, String ftype) {
        CoreReturnObject cro = new CoreReturnObject();
        try {
            if (StringUtils.isFtp) {
                // path=path.substring(path.indexOf("/",1));
                if (ftype.equals("file")) {
                    path = StringUtils.mainPath + path;
                    boolean isSuc = CoreFTPClient.delFile(path);
                    cro.setResult(isSuc);
                }
                else {
                    path = StringUtils.mainPath + path;
                    boolean isSuc = CoreFTPClient.delDirectory(path);
                    cro.setResult(isSuc);
                }
            }
            else {
                String rootPath = getPath();
                path = rootPath + path;
                boolean isSuc = DelFileOrFiles(path);
                cro.setResult(isSuc);
            }
        }
        catch (Exception e) {
            cro = cro.SetErrInfo("删除目录失败！" + e.getMessage());
        }
        return cro;
    }

    /* ===================================================================== */
    /**
     * 创建文件夹
     * @param path
     * @return
     */
    private boolean CreateFiles(String path) {
        if (path == null || path.trim().length() == 0) {
            return false;
        }
        File file = new File(path);
        try {
            if (!file.exists()) {
                file.mkdir();
            }
            else {
                return false;
            }
        }
        catch (Exception ex) {
            throw (new CoreException(ex.getMessage()));
        }
        return true;
    }

    private boolean DelFileOrFiles(String path) {
        if (path == null || path.trim().length() == 0) {
            return false;
        }
        File file = new File(path);
        try {
            if (file.exists()) {
                if (file.isFile()) {
                    file.delete();
                }
                else if (file.isDirectory()) {
                    File[] cFile = file.listFiles();
                    if (cFile.length > 0) {
                        for (int i = 0; i < cFile.length; i++) {
                            DelFileOrFiles(cFile[i].getPath());
                        }
                    }
                    file.delete();
                }
            }
            else {
                return false;
            }
        }
        catch (Exception ex) {
            throw (new CoreException(ex.getMessage()));
        }
        return true;
    }

    /*
     * 写文件
     */
    private boolean WriteFile(String path, String Content) {
        if (path == null || path.trim().length() == 0) {
            return false;
        }
        if (Content == null || Content.trim().length() == 0) {
            return false;
        }
        int index = path.lastIndexOf("/");
        String updatePath = path.substring(0, index);//
        File checkSpaceh = new File(updatePath);
        long freeSpace = checkSpaceh.getFreeSpace() / 1024 / 1024;
        if (freeSpace < 2) {
            throw (new CoreException("磁盘空间不足，保存配置文件filelist.xml失败"));
        }

        File file = new File(path);
        FileOutputStream out;

        try {
            if (!file.exists()) {
                file.createNewFile();
            }
            else {
                file.delete();
            }
            out = new FileOutputStream(file, false);
            StringBuffer sb = new StringBuffer();
            sb.append(Content);
            out.write(sb.toString().getBytes("utf-8"));
            out.close();
        }
        catch (Exception e) {
            throw (new CoreException(e.getMessage()));
            // return false;
        }
        return true;
    }

    /**
     * 读filelist.xml文件
     * @param f
     * @return
     */
    private String readFiletoString(File f) {
        InputStream is = null;
        String ret = null;
        try {
            is = new BufferedInputStream(new FileInputStream(f));
            long contentLength = f.length();
            ByteArrayOutputStream outstream = new ByteArrayOutputStream(
                    contentLength > 0 ? (int) contentLength : 1024);
            byte[] buffer = new byte[4096];
            int len;
            while ((len = is.read(buffer)) > 0) {
                outstream.write(buffer, 0, len);
            }
            outstream.close();
            ret = outstream.toString("utf-8");//
            // byte[]ba=outstream.toByteArray();
            // ret=newString(ba);
        }
        catch (Exception ex) {
            throw (new CoreException(ex.getMessage()));
        }
        finally {
            if (is != null) {
                try {
                    is.close();
                    is = null;
                    f = null;
                }
                catch (Exception e) {
                    throw (new CoreException(e.getMessage()));
                }
            }
        }
        return ret;

    }

    /**
     * 获取上传目录内信息
     * @param path
     */
    @SuppressWarnings("unchecked")
    private void readUpLoadDirectory(String path, String rpath, List directory) {
        File file = new File(path);
        File[] tempList = file.listFiles();
        for (int i = 0; i < tempList.length; i++) {
            File f = tempList[i];
            if (f.getName().equals("META-INF") || f.getName().equals("WEB-INF")
                    || f.getName().equals("index.jsp")) {
                continue;
            }
            if (f.isFile()) {
                Map result = new ListOrderedMap();
                result.put("filename", f.getName());
                result.put("ftype", "file");
                String npath = rpath
                        + (f.getPath().substring(f.getParent().length()))
                                .replace("\\", "/");
                result.put("path", npath);
                result.put("root", rpath);
                directory.add(result);
            }
            if (f.isDirectory()) {
                Map result = new ListOrderedMap();
                result.put("filename", f.getName());
                result.put("ftype", "directory");
                String npath = rpath
                        + (f.getPath().substring(f.getParent().length()))
                                .replace("\\", "/");
                result.put("path", npath);
                result.put("root", rpath);
                directory.add(result);
                readUpLoadDirectory(f.getPath(), npath, directory);

            }
        }
    }

    /**
     * 获取上传目录根地址
     * @param filename
     * @param content
     */
    private String getPath() {
        String path = "";
        try {
            path = Thread.currentThread().getContextClassLoader()
                    .getResource("/").getPath();// getClass().getProtectionDomain().getCodeSource().getLocation().getPath();//
            if (path.indexOf("WEB-INF") > 0) {
                path = path.substring(0, path.indexOf("/WEB-INF/classes"));
            }
            path = path.replace("%20", " ");
        }
        catch (Exception ex) {
            throw (new CoreException(ex.getMessage()));
        }
        return path;
    }

    private void upLoadFile(String filename, byte[] content) throws IOException {
        File f = new File(filename);
        if (f.exists()) {
            // 备份客户端更新文件
            String backPath = this.getPath() + "/backup/";
            String datestr = DateAndStringFormat.dataTimeToString2(Calendar
                    .getInstance().getTime());
            File backFile = new File(backPath
                    + f.getName().substring(0, f.getName().lastIndexOf("."))
                    + "_" + datestr
                    + f.getName().substring(f.getName().lastIndexOf(".")));

            if (!backFile.exists()) {
                File parentFile = backFile.getParentFile();
                if (parentFile != null && !parentFile.exists()) {
                    parentFile.mkdirs();
                }
                backFile.createNewFile();
            }
            InputStream backIs = new FileInputStream(f);
            OutputStream backOs = new FileOutputStream(backFile);
            byte[] buffer = new byte[1024];
            while (backIs.read(buffer) > 1) {
                backOs.write(buffer);
            }
            backIs.close();
            backOs.close();
        }
        else {
            try {
                f.createNewFile();
            }
            catch (IOException e) {
                throw (new CoreException(e.getMessage()));
            }
        }
        OutputStream os = null;
        try {
            os = new FileOutputStream(filename);
            os.write(content);
            // os.close();
        }
        catch (FileNotFoundException e) {
            throw (new CoreException("文件未找到！"));
        }
        catch (IOException e) {
            if (f.length() == 0 && f.exists()) {
                f.delete();
            }
            throw (new CoreException(e.getMessage()));
        }
        finally {
            try {
                if (os != null) {
                    os.close();
                }
            }
            catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
