package com.union.ai.api.client.service.impl;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.union.ai.api.client.service.LogWriterService;

import lombok.extern.slf4j.Slf4j;

/**
 * Created by IntelliJ IDEA.
 * Author: xingxin.jing
 * Date: 2019/4/18
 * Time: 上午11:53
 */
@Slf4j
@Service
public class LogWriterServiceImpl implements LogWriterService {

    @Value("${log.file.dir}")
    private String logFileDir;

    @Value("${write.log.thread.num}")
    private Integer threadNum;

    private ExecutorService executorService;

    private Lock lock = new ReentrantLock();

//    private String fileHome;

    @PostConstruct
    private void init() {
        log.info("日志文件写入线程池数量为：{}", threadNum);
        executorService = Executors.newFixedThreadPool(threadNum);
        if (StringUtils.isBlank(logFileDir)) {
            log.warn("日志文件路径为空,请在filters-${env}.properties文件中配置");
            throw new RuntimeException("日志文件路径为空,");
        }
//        String[] split = logFileDir.split("\\.");
//        StringBuilder userHome = new StringBuilder("/chroot");
//        for (String dir : split) {
//            userHome.append(File.separator).append(dir);
//        }
//        fileHome = userHome.toString();
        File file = new File(logFileDir);
        if(!file.exists())
        {
            file.mkdirs();
        }
        log.info("fileHome={}",logFileDir);
    }

    @Override
    public String asynWriteLog(final String appId, final String param) {

        String alphabetic = RandomStringUtils.randomAlphabetic(5).toLowerCase();
        final String fileName = System.currentTimeMillis() + "_" + alphabetic + ".txt";
        final String url = logFileDir + File.separator + appId + File.separator + fileName;
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                File file = new File(logFileDir + File.separator + appId);
                if (!file.exists())
                {
                    try
                    {
                        lock.lock();
                        File fileR = new File(logFileDir + File.separator + appId);
                        if (!fileR.exists())
                        {
                            fileR.mkdirs();
                        }
                    }
                    catch (Exception e)
                    {
                        log.error("创建file错误，appId=" + appId, e);
                    }
                    finally
                    {
                        lock.unlock();
                    }
                }
                try {
                    File writename = new File(url);
                    writename.createNewFile(); // 创建新文件
                    BufferedWriter out = new BufferedWriter(new FileWriter(writename));
                    out.write(param); // \r\n即为换行
                    out.flush(); // 把缓存区内容压入文件
                    out.close(); // 最后记得关闭文件
                    log.info("url={} 保存成功", url);
                } catch (IOException e) {
                    log.error("appid=" + appId + "存储文件失败", e);
                }
            }
        });
        return url;
    }

    @Override
    public String synWriteLog(String appId, String param)
    {
        String alphabetic = RandomStringUtils.randomAlphabetic(5).toLowerCase();
        String fileName = System.currentTimeMillis() + "_" + alphabetic + ".txt";
        String url = logFileDir + File.separator + appId + File.separator + fileName;
        File file = new File(logFileDir + File.separator + appId);
        if (!file.exists()) {
            try {
                lock.lock();
                File fileR = new File(logFileDir + File.separator + appId);
                if (!fileR.exists()) {
                    fileR.mkdirs();
                }
            } catch (Exception e) {
                log.error("创建file错误，appId=" + appId, e);
            } finally {
                lock.unlock();
            }
        }
        try {
            File writename = new File(url); // 相对路径，如果没有则要建立一个新的output。txt文件
            writename.createNewFile(); // 创建新文件
            BufferedWriter out = new BufferedWriter(new FileWriter(writename));
            out.write(param); // \r\n即为换行
            out.flush(); // 把缓存区内容压入文件
            out.close(); // 最后记得关闭文件
            log.info("url={} 保存成功", url);
        } catch (IOException e) {
            log.error("appid=" + appId + "存储文件失败", e);
        }
        return url;
    }

    public void destroy() {
        if (executorService != null) {
            executorService.shutdown();
        }
    }

}
