package com.its.wthr.webapp.service;

import com.its.app.utils.OS;
import com.its.wthr.webapp.vo.FileInfoVo;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

@Service
public class FileService {
	private static final Logger log = LoggerFactory.getLogger(FileService.class);
	private final String sysDir = System.getProperty("user.dir");
	private final String[] exceptDir = new String[]{"backup"};
	private int id = 1;

	public String getView(HttpServletRequest request, String fileName, String filePath) {
		long preEndPoint = request.getParameter("preEndPoint") == null
				? 0L
				: Long.parseLong(request.getParameter("preEndPoint") + "");
		StringBuilder sb = new StringBuilder();
		RandomAccessFile file = null;
		String errMsg = "";

		try {
			file = new RandomAccessFile(System.getProperty("user.dir") + filePath + fileName, "r");
			long endPoint = file.length();
			long startPoint = preEndPoint > 0L ? preEndPoint : (endPoint < 2000L ? 0L : endPoint - 2000L);
			file.seek(startPoint);

			String str;
			while ((str = file.readLine()) != null) {
				byte[] b = str.getBytes("iso-8859-1");
				str = new String(b, "UTF-8");
				sb.append(str);
				sb.append("<br>");
				endPoint = file.getFilePointer();
				file.seek(endPoint);
			}

			JSONObject json = new JSONObject();
			json.put("endPoint", endPoint);
			json.put("log", sb.toString());
			String var15 = json.toString();
			return var15;
		} catch (FileNotFoundException var27) {
			log.error("FileService.getView: Exception: {}", var27.toString());
			errMsg = errMsg + var27.toString();
		} catch (IOException var28) {
			log.error(var28.getMessage());
			errMsg = errMsg + var28.toString();
		} finally {
			try {
				if (file != null) {
					file.close();
				}
			} catch (Exception var26) {
				log.error("FileService.getView: Exception: {}", var26.toString());
				errMsg = errMsg + var26.toString();
			}

		}

		if (!errMsg.equals("")) {
			sb.append(errMsg);
			sb.append("<br>");
			JSONObject json = new JSONObject();
			json.put("endPoint", 0);
			json.put("log", sb.toString());
			return json.toString();
		} else {
			return null;
		}
	}

	public ResponseEntity<Resource> fileDownload(String fileName, String filePath) {
		try {
			Path path = Paths.get(System.getProperty("user.dir") + filePath + fileName);
			String contentType = "application/download";
			HttpHeaders headers = new HttpHeaders();
			headers.add("Content-Type", contentType);
			headers.setContentDisposition(ContentDisposition.parse("attachment; filename=\"" + fileName + "\";"));
			Resource resource = new InputStreamResource(Files.newInputStream(path));
			return new ResponseEntity<>(resource, headers, HttpStatus.OK);
		} catch (IOException var7) {
			log.error("FileService.fileDownload: Exception: {}", var7.toString());
			return null;
		}
	}

	public void fileDelete(String fileName, String filePath) {
		File file = new File(this.sysDir + filePath + fileName);
		if (file.exists()) {
			if (file.delete()) {
				log.info("FileService.fileDelete: Delete Success: {}", filePath + fileName);
			} else {
				log.error("FileService.fileDelete: Delete Fail: {}", filePath + fileName);
			}
		} else {
			log.warn("FileService.fileDelete: Not exists: {}", filePath + fileName);
		}

	}

	public List<FileInfoVo> getLogFiles() {
		this.id = 1;
		FileInfoVo rootFile = new FileInfoVo();
		rootFile.setId(this.id);
		rootFile.setType("dir");
		++this.id;
		rootFile.setFileName("logs");
		String var10002 = this.sysDir;
		this.getClass();
		rootFile.setFileInfos(this.getFiles(var10002, "/logs/"));
		List<FileInfoVo> fileInfos = new ArrayList<>();
		fileInfos.add(rootFile);
		return fileInfos;
	}

	private List<FileInfoVo> getFiles(String sysDir, String logDir) {
		int rootId = this.id - 1;
		List<FileInfoVo> subArr = new ArrayList<>();
		File dirFile = new File(sysDir, logDir);
		File[] fileList = dirFile.listFiles();
		File[] var7 = fileList;
		int var8 = fileList.length;

		int var9;
		File file;
		FileInfoVo info;
		for (var9 = 0; var9 < var8; ++var9) {
			file = var7[var9];
			info = new FileInfoVo();
			if (file.isDirectory()) {
				String[] var12 = this.exceptDir;
				int var13 = var12.length;

				for (int var14 = 0; var14 < var13; ++var14) {
					String dir = var12[var14];
					if (dir.equals(file.getName())) {
						break;
					}

					String subDir = file.getPath().substring(file.getPath().indexOf(logDir.replaceAll("/", "")),
							file.getPath().length());
					info.setId(this.id);
					++this.id;
					String sFileSeparator = "/";
					info.setFilePath(sFileSeparator + subDir);
					info.setFileName(file.getName());
					info.setFileSize(file.length());
					info.setType("dir");
					info.setFileInfos(this.getFiles(sysDir, subDir));
					info.setParentId(rootId);
					subArr.add(info);
				}
			}
		}

		var7 = fileList;
		var8 = fileList.length;

		for (var9 = 0; var9 < var8; ++var9) {
			file = var7[var9];
			info = new FileInfoVo();
			if (file.isFile() && file.getName().contains(".log")) {
				info.setId(this.id);
				++this.id;
				info.setFileName(file.getName());
				info.setFileSize(file.length());
				String subDir;
				if (OS.isWindows()) {
					subDir = file.getPath().substring(file.getPath().indexOf(logDir.replaceAll("/", "")),
							file.getPath().length() - file.getName().length()).replaceAll("\\\\", "/");
				} else {
					subDir = file.getPath().substring(file.getPath().indexOf(logDir),
							file.getPath().length() - file.getName().length()).replaceAll("\\\\", "/");
				}

				String sFileSeparator = "/";
				info.setFilePath(sFileSeparator + subDir);
				info.setType("log");
				info.setParentId(rootId);
				subArr.add(info);
			}
		}

		return subArr;
	}
}