package com.qst.dms.service;
import java.io.EOFException;
import java.io.*;
import java.io.FileNotFoundException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.InputMismatchException;
import java.util.Scanner;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

import com.qst.dms.db.DBUtil;
import com.qst.dms.entity.*;
import com.sun.net.httpserver.Request;

//日志业务类
public class LogRecService {
	// 日志数据采集
	public LogRec inputLog() {
		LogRec log = null;
		// 建立一个从键盘接收数据的扫描器
		Scanner scanner = new Scanner(System.in);
		try {
			// 提示用户输入ID标识
			System.out.println("请输入ID标识：");
			// 接收键盘输入的整数

			int id =0;
			for(;;)
			try
			{
				id = scanner.nextInt();
				break;
			}
			catch(InputMismatchException e)
			{
				System.out.println("输入数据不合法，请重新输入");
				scanner.nextLine();
			}
			// 获取当前系统时间
			Date nowDate = new Date();
			// 提示用户输入地址
			System.out.println("请输入地址：");
			// 接收键盘输入的字符串信息
			String address = scanner.next();
			// 数据状态是“采集”
			int type = DataBase.GATHER;
			// 提示用户输入登录用户名
			System.out.println("请输入登录用户名：");
			// 接收键盘输入的字符串信息
			String user = scanner.next();
			// 提示用户输入主机IP
//			System.out.println("请输入主机IP：");
//			// 接收键盘输入的字符串信息
//			String ip = scanner.next();
			String ip = "";
			try {
				Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
				while (interfaces.hasMoreElements()) {
					NetworkInterface iface = interfaces.nextElement();
					// 过滤回环接口和虚拟接口
					if (iface.isLoopback() || iface.isVirtual() || !iface.isUp()) {
						continue;
					}
					Enumeration<InetAddress> addresses = iface.getInetAddresses();
					while (addresses.hasMoreElements()) {
						ip = addresses.nextElement().getHostAddress();
					}
				}

			} catch (SocketException e) {
				e.printStackTrace();
			}
			// 提示用户输入登录状态、登出状态
			System.out.println("请输入登录状态:1是登录，0是登出");
			int logType = 0;
			for(;;)
				try
				{
					logType = scanner.nextInt();
					if(logType!=0&&logType!=1)
						throw new InputMismatchException();
					break;
				}
				catch(InputMismatchException e)
				{
					System.out.println("输入数据不合法，请重新输入");
					scanner.nextLine();
				}
			// 创建日志对象
			log = new LogRec(id, nowDate, address, type, user, ip, logType);
		} catch (Exception e) {
			System.out.println("采集的日志信息不合法");
		}
		// 返回日志对象
		return log;
	}

	public ArrayList<MatchedLogRec> readMatchLog()
	{
		ArrayList<MatchedLogRec> matchedLogs = new ArrayList<>();
		try(ObjectInputStream OIStream = new ObjectInputStream(new FileInputStream("MatchLogs.txt")))
		{
			MatchedLogRec matchLog;
			while((matchLog = (MatchedLogRec) OIStream.readObject())!=null)
				matchedLogs.add(matchLog);
		}
		catch(FileNotFoundException ex)
		{
			;
		}
		catch(EOFException ex)
		{
			;
		}
		catch(Exception Ex)
		{
			Ex.printStackTrace();
		}
		return matchedLogs;
	}
	public ArrayList<MatchedLogRec> readMatchedLogFromDB() throws SQLException
	{
		ArrayList<MatchedLogRec>matchedLogRecs = new ArrayList<>();
		DBUtil db = new DBUtil();
		try
		{
			db.getConnection();
			String sql = "select i.id,i.time,i.address,i.type,i.username,i.ip,i.logtype,"+
					"o.id,o.time,o.address,o.type,o.username,o.ip,o.logtype "+
					"from matched_logrec m,gather_logrec i,gather_logrec o "+
					"where m.loginid=i.id AND m.logoutid=o.id;";
			ResultSet resultSet = db.executeQuery(sql,null);
			while(resultSet.next())
			{
				Object[] temp = new Object[7];
				for(int i=1;i<=7;i++)
					temp[i-1] = resultSet.getObject(i);
				LogRec login = LogRec.get_LogRec(temp);
				for(int i=8;i<=14;i++)
					temp[i-8] = resultSet.getObject(i);
				LogRec logout = LogRec.get_LogRec(temp);
				matchedLogRecs.add(new MatchedLogRec(login,logout));
			}
			db.closeAll();
		}
		catch (SQLException e)
		{
			throw e;
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		return matchedLogRecs;
	}

	public void saveMatchLog(ArrayList<MatchedLogRec>matchLogs)
	{
		try{
			ObjectOutputStream obStream = new ObjectOutputStream(new FileOutputStream("MatchLogs.txt"));
			for(MatchedLogRec log:matchLogs)
			{
				if(log==null)
					continue;
				obStream.writeObject(log);
				obStream.flush();
			}
			//null 代表结尾
			obStream.writeObject(null);
			obStream.close();
		}catch(Exception Ex)
		{
			Ex.printStackTrace();
		}
	}

	public void saveAndAppendMatchLog(ArrayList<MatchedLogRec>matchLogs)
	{
		if(matchLogs==null)
			return;
		try
		{
			File file = new File("MatchLogs.txt");
			AppendObjectOutputStream.file = file;
			AppendObjectOutputStream AOOStream = new AppendObjectOutputStream();
			for(MatchedLogRec log:matchLogs)
			{
				if(log==null)
					continue;
				AOOStream.writeObject(log);
				AOOStream.flush();
			}
			//null 代表结尾
			//AOOStream.writeObject(null);
			AOOStream.close();
		}
		catch (Exception Ex)
		{
			Ex.printStackTrace();
		}
	}
	public void saveMatchLogToDB(ArrayList<MatchedLogRec>matchLogs)
	{
		DBUtil db = new DBUtil();
		try
		{
			db.getConnection();
			for(MatchedLogRec logRec:matchLogs)
			{
				LogRec login = logRec.getLogin();
				LogRec logout = logRec.getLogout();
				//信息
				String sql = "INSERT INTO gather_logrec(id,time,address,type,username,ip,logtype) VALUES(?,?,?,?,?,?,?)";
				db.executeUpdate(sql, login.get_DB_param());
				db.executeUpdate(sql, logout.get_DB_param());
				//匹配对
				sql = "INSERT INTO matched_logrec(loginid,logoutid) VALUES(?,?)";
				db.executeUpdate(sql, logRec.get_DB_param());
			}
			db.closeAll();
		} catch(Exception e)
		{
			e.printStackTrace();
		}
    }


	// 日志信息输出
	public void showLog(LogRec... logRecs) {
		for (LogRec e : logRecs) {
			if (e != null) {
				System.out.println(e.toString());
			}
		}
	}
	// 匹配日志信息输出，可变参数
	public void showMatchLog(MatchedLogRec... matchLogs) {
		for (MatchedLogRec e : matchLogs) {
			if (e != null) {
				System.out.println(e.toString());
			}
		}
	}

	// 匹配日志信息输出,参数是集合
	public void showMatchLog(ArrayList<MatchedLogRec> matchLogs) {
		for (MatchedLogRec e : matchLogs) {
			if (e != null) {
				System.out.println(e.toString());
			}
		}
	}

}
