package com.kmall.common.fileserver.util;

import com.kmall.common.fileserver.common.NameValuePair;
import com.kmall.common.fileserver.fastdfs.*;
import org.apache.log4j.Logger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.Serializable;
import java.util.UUID;

public class FileManager implements Serializable {

    private static final long serialVersionUID = -9042217554595446459L;

    public static final String PROTOCOL = "http://";

    public static final String SEPARATOR = "/";
    public static final String COLON = ":";


    /**
     * 配置文件名字
     */
    public static final String CLIENT_CONFIG_FILE = "conf/fastdfs.properties";

    private static Logger logger = Logger.getLogger(FileManager.class);

    private static TrackerClient trackerClient;
    private static TrackerServer trackerServer;
    private static StorageServer storageServer;
    private static StorageClient storageClient;

    static {
        System.out.println("FileManager");
        try {
            String fdfsClientConfigFilePath = CLIENT_CONFIG_FILE;
            ClientGlobal.init(fdfsClientConfigFilePath);

            trackerClient = new TrackerClient();
            trackerServer = trackerClient.getConnection();

            storageClient = new StorageClient(trackerServer, storageServer);

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

    /**
     * <strong>方法概要： 文件上传</strong> <br>
     * <strong>创建时间： 2016-9-26 上午10:26:11</strong> <br>
     *
     * @param FastDFSFile file
     * @return fileAbsolutePath
     * @author Wang Liang
     */
    public static String upload(MultipartFile attach) {
        String[] uploadResults = null;
        String ext = attach.getOriginalFilename().substring(attach.getOriginalFilename().lastIndexOf(".") + 1);
        try {
            FastDFSFile file = new FastDFSFile(attach.getBytes(), ext);
            NameValuePair[] meta_list = new NameValuePair[4];
            meta_list[0] = new NameValuePair("fileName", attach.getOriginalFilename());
            meta_list[1] = new NameValuePair("fileLength", String.valueOf(attach.getSize()));
            meta_list[2] = new NameValuePair("fileExt", ext);
            meta_list[3] = new NameValuePair("fileAuthor", ClientGlobal.file_author);
            synchronized (storageClient) {
                uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        String groupName = uploadResults[0];
        String remoteFileName = uploadResults[1];

        String httpAddr = ClientGlobal.http_tracket_nginx_addr;

        String httpPort = ClientGlobal.http_tracket_server_port;

        String fileAbsolutePath = PROTOCOL + httpAddr + COLON + httpPort + SEPARATOR + groupName + SEPARATOR + remoteFileName;
        return fileAbsolutePath;
    }


    /**
     * <strong>方法概要： 文件上传</strong> <br>
     * <strong>创建时间： 2016-9-26 上午10:26:11</strong> <br>
     *
     * @return fileAbsolutePath
     * @author Wang Liang
     */
    public static String upload(String originalFileName, byte[] content, String fileLength) {
        String[] uploadResults = null;
        String ext = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
        try {
            FastDFSFile file = new FastDFSFile(content, ext);
            NameValuePair[] meta_list = new NameValuePair[4];
            meta_list[0] = new NameValuePair("fileName", originalFileName);
            meta_list[1] = new NameValuePair("fileLength", fileLength);
            meta_list[2] = new NameValuePair("fileExt", ext);
            meta_list[3] = new NameValuePair("fileAuthor", ClientGlobal.file_author);
            synchronized (storageClient) {
                uploadResults = storageClient.upload_file(file.getContent(), file.getExt(), meta_list);
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        String groupName = uploadResults[0];
        String remoteFileName = uploadResults[1];

        String httpAddr = ClientGlobal.http_tracket_nginx_addr;

        String httpPort = ClientGlobal.http_tracket_server_port;

        String fileAbsolutePath = PROTOCOL + httpAddr + COLON + httpPort + SEPARATOR + groupName + SEPARATOR + remoteFileName;
        return fileAbsolutePath;
    }

    /**
     * <strong>方法概要： 文件下载</strong> <br>
     * <strong>创建时间： 2016-9-26 上午10:28:21</strong> <br>
     *
     * @param String groupName
     * @param String remoteFileName
     * @return returned value comment here
     * @author Wang Liang
     */
    public static ResponseEntity<byte[]> download(String filePath, String fileName) {
        byte[] content = null;
        HttpHeaders headers = new HttpHeaders();
        String substr = filePath.substring(filePath.indexOf("group"));
        String groupName = substr.split("/")[0];
        String remoteFileName = substr.substring(substr.indexOf("/") + 1);
        String specFileName = substr.substring(substr.indexOf("."));
        try {
            if (fileName == null || fileName.trim().equals("")) {
                fileName = UUID.randomUUID() + specFileName;
            } else {
                fileName = fileName + specFileName;
            }
            content = storageClient.download_file(groupName, remoteFileName);
            headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("UTF-8"), "iso-8859-1"));
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseEntity<byte[]>(content, headers, HttpStatus.CREATED);
    }

    public static FileInfo getFile(String filePath) {
        String substr = filePath.substring(filePath.indexOf("group"));
        String groupName = substr.split("/")[0];
        String remoteFileName = substr.substring(substr.indexOf("/") + 1);
        try {
            return storageClient.get_file_info(groupName, remoteFileName);
        } catch (IOException e) {
            logger.error("IO Exception: Get File from Fast DFS failed", e);
        } catch (Exception e) {
            logger.error("Non IO Exception: Get File from Fast DFS failed", e);
        }
        return null;
    }
}
