package com.community.huiju.log;

import java.io.File;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.TimerTask;

/**
 * 日志工厂
 * @author weiximei
 */
public class LogFactory {

    public static File getFile() {
        LocalDate localDate = LocalDate.now();
        String pathMkdir = "";

        String os = System.getProperty("os.name");
        if(os.toLowerCase().startsWith("win")){
            pathMkdir = "E:" + File.separator + "log" + File.separator + "foreign-log" + File.separator + localDate.getYear() + "-" + localDate.getMonthValue() + "-" + localDate.getDayOfMonth();
        } else {
            pathMkdir = "/home/fxf/smart-community" + File.separator + "log" + File.separator + "foreign-log" + File.separator + localDate.getYear() + "-" + localDate.getMonthValue() + "-" + localDate.getDayOfMonth();
        }

        File file = new File(pathMkdir);
        if (!file.exists()) {
            file.mkdirs();
        }
        file = new File(pathMkdir + File.separator + "foreign-log.log");

        return file;
    }

    /**
     * 记录请求参数和返回值
     * @param parameters
     * @param returnValue
     * @return
     */
    public static TimerTask parametersAndReturn(String parameters, String returnValue){
        return new TimerTask() {
            @Override
            public void run() {

                RandomAccessFile accessFile = null;
                FileChannel fileChannel = null;
                FileLock fileLock = null;
                try {
                    // 获取这个文件的读和写的权限
                    accessFile = new RandomAccessFile(getFile(), "rw");
                    // 文件通道
                    fileChannel = accessFile.getChannel();
                    fileLock = null;
                    while (true) {
                        try {
                            // 获取锁，如果失败，继续尝试
                            fileLock = fileChannel.tryLock();
                            break;
                        } catch (Exception e) {
                            Thread.sleep(100);
                        }
                    }

                    // 获取当前这个文件的大小
                    long length = accessFile.length();
                    // 设置写入的指针, 设置到这个文件的末尾
                    accessFile.seek(length);
                    // 开始写入文件
                    LocalDateTime localDateTime = LocalDateTime.now();
                    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss");
                    String str = dateTimeFormatter.format(localDateTime) + " === " + Thread.currentThread().getName() + "  : " + parameters + "\n";
                    fileChannel.write(ByteBuffer.wrap(str.getBytes()));
                    str = dateTimeFormatter.format(localDateTime) + " === " + Thread.currentThread().getName() + "  : " + returnValue + "\n";
                    fileChannel.write(ByteBuffer.wrap(str.getBytes()));

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (fileLock != null && fileChannel != null && accessFile != null) {
                        // 释放锁
                        try {
                            fileLock.release();
                            fileChannel.close();
                            accessFile.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }


            }
        };
    }

}
