package com.hyd.redisfx.conn;

import com.alibaba.fastjson.JSON;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

public class ConnectionManager {

    private static final Logger LOG = LoggerFactory.getLogger(ConnectionManager.class);

    private static final String saveFilePath = System.getProperty("user.home") + "/.redisfx/connections.json";

    private static boolean canSave = true;

    private static ObservableList<Connection> connections = null;

    static {
        File file = new File(saveFilePath);

        try {
            if (!file.exists()) {
                File parent = file.getParentFile();
                if (!parent.exists() && !parent.mkdirs()) {
                    canSave = false;
                }
                if (!file.createNewFile()) {
                    canSave = false;
                }
                connections = FXCollections.observableArrayList();
            } else {
                String json = FileUtils.readFileToString(file, "UTF-8");
                connections = FXCollections.observableArrayList(JSON.parseArray(json, Connection.class));
            }
        } catch (IOException e) {
            LOG.error("", e);
            canSave = false;
        }
    }

    public static void saveConnection(Connection connection) {

        if (!connections.contains(connection)) {
            connections.add(connection);
        } else {
            int index = connections.indexOf(connection);
            connections.set(index, connection);
        }

        try {
            File file = new File(saveFilePath);
            FileUtils.write(file, JSON.toJSONString(new ArrayList<>(connections), true), "UTF-8");
        } catch (IOException e) {
            LOG.error("", e);
        }
    }

    public static ObservableList<Connection> connectionsProperty() {
        return connections;
    }
}

@@ -315,16 +315,39 @@
 rayList;
+%0Aimport java.util.List;
 %0A%0Apublic
@@ -1240,97 +1240,328 @@
     
-connections = FXCollections.observableArrayList(JSON.parseArray(json, Connection.class));
+List%3CConnection%3E connectionList = JSON.parseArray(json, Connection.class);%0A%0A                if (connectionList != null) %7B%0A                    connections = FXCollections.observableArrayList(connectionList);%0A                %7D else %7B%0A                    connections = FXCollections.observableArrayList();%0A                %7D
 %0A   

manage invalid config file content