package cn.stylefeng.guns.zjxlUtil;

import org.apache.commons.io.FileUtils;
import org.csource.fastdfs.ClientGlobal;
import org.csource.fastdfs.StorageClient;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

/**
 * Created by szx on 2015/9/19.
 */
public class FastDFSClientPool {
    private static volatile FastDFSClientPool pool;
    private Logger logger = (Logger) LoggerFactory.getLogger(FastDFSClientPool.class);
    private Map<StorageClient, Boolean> map;

    private int maxPoolSize = 20;
    private int waitTime = 500;
    private int initPoolSize = 5;

    {
        try {

            String basePath = FastDFSClientPool.class.getResource("/").getPath();
    //        ClientGlobal.init("/data/guns-separation/config/fdfs_client.conf");//测试环境固定使用
            Resource resource = new ClassPathResource("/config/fdfs_client.conf");
            InputStream inputStream = resource.getInputStream();
            long time = System.currentTimeMillis();
            String pathName = time + "fdfs_client.conf";
            File file = new File(pathName);
            try {
                //将读取到的类容存储到临时文件中，后面就可以用这个临时文件访问了
                FileUtils.copyInputStreamToFile(inputStream,file);
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("********************************************************"+file.getName());
            ClientGlobal.init(file.getName());//
            deleteFolder(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void deleteFolder(File folder){
        File[] files  = folder.listFiles();
        if (files != null){
            for(File f: files){
                if (f.isDirectory()){
                    deleteFolder(f);
                }else {
                    f.delete();
                }
            }
        }
        folder.delete();
    }


    public  String readfile(String file){
        InputStream stream = this.getClass().getResourceAsStream(file);
        StringBuffer sb = new StringBuffer() ;
        BufferedReader br = null ;
        try {
            br = new BufferedReader(new InputStreamReader(stream,"UTF-8")) ;
            String s=null ;
            while((s=br.readLine()) !=null){
                sb.append(s) ;
            }
            br.close();
        } catch (FileNotFoundException e) {
            logger.error("FileNotFoundException:"+e);
        } catch (IOException e) {
            logger.error("IOException :"+e);
        } finally {
            if(br !=null){
                try {
                    br.close();
                } catch (IOException e) {
                    logger.error("close br error:"+e);
                }
            }
        }
        return sb.toString();
    }

    private FastDFSClientPool() {

        init();
    }

    public static FastDFSClientPool getInstance() {
        if (pool == null) {
            synchronized (FastDFSClientPool.class) {
                if(pool == null) {
                    pool = new FastDFSClientPool();
                }
            }
        }
        System.out.println("FastDFSClientPool:"+pool.toString());
        return pool;
    }

    private void init() {
        try {

            map = new HashMap<StorageClient, Boolean>();

            //不做初始缓存
//            for (int i = 0; i < initPoolSize; i++) {
//                map.put(getNewStorageClient(), true);
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public TrackerServer getTrackerServer(){
        try {
            TrackerClient tracker = new TrackerClient();
            return tracker.getConnection();
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;

    }

    private StorageClient getNewStorageClient() {
        try {
            TrackerClient tracker = new TrackerClient();
            logger.info("FastDFSClientPool→tracker==="+tracker);
            TrackerServer trackerServer = tracker.getConnection();
            logger.info("FastDFSClientPool→trackerServer   ===   "+trackerServer);
            StorageClient client = new StorageClient(trackerServer, null);
            return client;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public synchronized StorageClient getStorageClient() {
        StorageClient client = null;
        try {
            for (Entry<StorageClient, Boolean> entry : map.entrySet()) {
                if (entry.getValue()) {
                    client = entry.getKey();
                    System.out.println("从缓存中获得fastdfs client");
                    map.put(client, false);
                    break;
                }
            }
            if (client == null) {
                if(map.size()<maxPoolSize) {
                    System.out.println("创建新fastdfs client:");
                    client = getNewStorageClient();
                    map.put(client, false);
                }

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

    public void releaseStorageClient(StorageClient client) {
        if (client == null) {
            return;
        }
        try {
            if(map.containsKey(client)) {
                    map.put(client, true);

            } else {
                client =null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
