package com.ecep.contract;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import lombok.Getter;
import lombok.Setter;

/**
 * 应用程序配置类，用于管理系统配置信息
 */
@Component
public class MyProperties implements InitializingBean {
    private static final Logger logger = LoggerFactory.getLogger(MyProperties.class);
    private static final String FILE_NAME = "config.properties";

    @Getter
    @Setter
    private String downloadsPath;

    @Getter
    @Setter
    private String serverHost;

    @Getter
    @Setter
    private String serverPort;

    @Getter
    @Setter
    private String userName;

    @Getter
    @Setter
    private String password;

    @Getter
    @Setter
    private boolean rememberPassword;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 初始化时加载配置文件
        try {
            loadFromFile();
        } catch (Exception e) {
            logger.warn("初始化配置文件失败: {}", e.getMessage());
        }
    }

    /**
     * 从文件加载配置
     */
    public void loadFromFile() {
        File configFile = new File(FILE_NAME);
        if (!configFile.exists()) {
            logger.debug("配置文件不存在: {}", configFile.getPath());
            return;
        }

        try (FileInputStream input = new FileInputStream(configFile)) {
            Properties properties = new Properties();
            properties.load(input);
            loadFromProperties(properties);
            logger.debug("成功从配置文件加载配置: {}", configFile.getPath());
        } catch (Exception e) {
            logger.error("加载配置文件失败: {}", configFile.getPath(), e);
        }
    }

    /**
     * 设置Properties对象并加载配置
     * 用于从外部设置配置项
     * 
     * @param properties 配置对象
     */
    public void setProperties(Properties properties) {
        this.loadFromProperties(properties);
    }
    
    /**
     * 从Properties对象加载配置
     * 用于从config.properties文件中读取配置项
     * 
     * @param properties 配置对象
     */
    public void loadFromProperties(Properties properties) {
        if (properties == null) {
            logger.warn("Properties对象为空，无法加载配置");
            return;
        }

        // 加载下载路径配置
        String downloadsPath = properties.getProperty("my.downloadsPath");
        if (StringUtils.hasText(downloadsPath)) {
            this.setDownloadsPath(downloadsPath);
            logger.debug("从配置文件加载下载路径: {}", downloadsPath);
        }
        
        // 加载服务器配置
        String serverHost = properties.getProperty("server.host", "127.0.0.1");
        if (StringUtils.hasText(serverHost)) {
            this.setServerHost(serverHost);
            logger.debug("从配置文件加载服务器地址: {}", serverHost);
        }
        
        String serverPort = properties.getProperty("server.port", "8080");
        if (StringUtils.hasText(serverPort)) {
            this.setServerPort(serverPort);
            logger.debug("从配置文件加载服务器端口: {}", serverPort);
        }
        
        // 加载用户凭证配置
        String userName = properties.getProperty("user.name");
        if (StringUtils.hasText(userName)) {
            this.setUserName(userName);
            logger.debug("从配置文件加载用户名");
        }
        
        // 只有在记住密码的情况下才加载密码
        String rememberPasswordStr = properties.getProperty("user.rememberPassword");
        boolean rememberPassword = "true".equals(rememberPasswordStr);
        this.setRememberPassword(rememberPassword);
        
        if (rememberPassword) {
            String password = properties.getProperty("user.password");
            if (StringUtils.hasText(password)) {
                this.setPassword(password);
                logger.debug("从配置文件加载密码");
            }
        }
    }

    /**
     * 将配置保存到Properties对象
     * 用于将配置项保存到config.properties文件
     * 
     * @param properties 配置对象
     */
    public void saveToProperties(Properties properties) {
        if (properties == null) {
            logger.warn("Properties对象为空，无法保存配置");
            return;
        }

        // 保存下载路径配置
        if (StringUtils.hasText(getDownloadsPath())) {
            properties.setProperty("my.downloadsPath", getDownloadsPath());
            logger.debug("保存下载路径到配置文件: {}", getDownloadsPath());
        }
        
        // 保存服务器配置
        if (StringUtils.hasText(getServerHost())) {
            properties.setProperty("server.host", getServerHost());
            logger.debug("保存服务器地址到配置文件: {}", getServerHost());
        }
        
        if (StringUtils.hasText(getServerPort())) {
            properties.setProperty("server.port", getServerPort());
            logger.debug("保存服务器端口到配置文件: {}", getServerPort());
        }
        
        // 保存用户凭证配置
        if (StringUtils.hasText(getUserName())) {
            properties.setProperty("user.name", getUserName());
            logger.debug("保存用户名为配置文件");
        }
        
        properties.setProperty("user.rememberPassword", String.valueOf(isRememberPassword()));
        
        // 只有在记住密码的情况下才保存密码
        if (isRememberPassword() && StringUtils.hasText(getPassword())) {
            properties.setProperty("user.password", getPassword());
            logger.debug("保存密码到配置文件");
        } else if (properties.containsKey("user.password")) {
            // 如果不记住密码，删除已存在的密码配置
            properties.remove("user.password");
        }
    }

    /**
     * 尝试返回当前用户的下载文件夹
     */
    public File getDownloadDirectory() {
        String downloadsPath = getDownloadsPath();
        if (StringUtils.hasText(downloadsPath)) {
            // 确保目录存在
            File dir = new File(downloadsPath);
            if (!dir.exists()) {
                boolean created = dir.mkdirs();
                logger.debug("创建下载目录: {}, 结果: {}", downloadsPath, created);
            }
            return dir;
        }

        // 没有配置下载目录时，尝试使用默认设置
        String home = System.getProperty("user.home");
        Path path = Paths.get(home, "Downloads");
        return path.toFile();
    }

    /**
     * 保存配置到文件
     */
    public void save() {
        File configFile = new File(FILE_NAME);
        try (FileOutputStream output = new FileOutputStream(configFile)) {
            Properties properties = new Properties();
            
            // 如果文件已存在，先读取现有配置，避免覆盖其他配置
            if (configFile.exists()) {
                try (FileInputStream input = new FileInputStream(configFile)) {
                    properties.load(input);
                }
            }
            
            // 保存当前配置
            saveToProperties(properties);
            properties.store(output, "Contract Manager 应用程序配置");
            logger.debug("成功保存配置到文件: {}", configFile.getPath());
        } catch (Exception e) {
            logger.error("保存配置到文件失败: {}", configFile.getPath(), e);
        }
    }

}
