package com.flowci.core.common.service;

import com.flowci.core.common.dao.SettingsDao;
import com.flowci.core.common.domain.Settings;
import com.flowci.core.common.domain.Variables;
import com.flowci.core.common.manager.SpringTaskManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Optional;

@Service
public class SettingServiceImpl implements SettingService {

    @Autowired
    private Environment environment;

    @Autowired
    private ServerProperties serverProperties;

    @Autowired
    private SettingsDao settingsDao;

    @Autowired
    private SpringTaskManager taskManager;

    /**
     * Set default server url
     * value from FLOWCI_SERVER_URL or http://FLOWCI_SERVER_ADDRESS:FLOWCI_SERVER_PORT
     */
    @PostConstruct
    public void setDefaultValue() {
        taskManager.run("init-default-settings", () -> {
            Optional<Settings> optional = settingsDao.findById(Settings.DefaultId);
            if (!optional.isPresent()) {

                String address = serverProperties.getAddress().toString().replace("/", "");
                String serverUrl = environment.getProperty(
                        Variables.App.ServerUrl,
                        String.format("http://%s:%s", address, serverProperties.getPort())
                );

                Settings s = new Settings();
                s.setServerUrl(serverUrl);
                settingsDao.save(s);
            }
        });
    }

    @Override
    public Settings get() {
        return settingsDao.findById(Settings.DefaultId).get();
    }

    @Override
    public void save(Settings settings) {
        Settings o = get();
        o.setServerUrl(settings.getServerUrl());

        settingsDao.save(o);
    }
}

@@ -1159,52 +1159,9 @@
 d);%0A
-            if (!optional.isPresent()) %7B%0A%0A  
+%0A
     
@@ -1164,26 +1164,24 @@
             
-  
 String addre
@@ -1244,20 +1244,16 @@
 %22, %22%22);%0A
-    
         
@@ -1320,20 +1320,16 @@
         
-    
 Variable
@@ -1361,28 +1361,24 @@
             
- 
-   
 String.forma
@@ -1448,20 +1448,12 @@
     
-    );%0A%0A    
+);%0A%0A
     
@@ -1485,28 +1485,116 @@
 Settings();%0A
+%0A
     
+        if (optional.isPresent()) %7B%0A                s = optional.get();%0A            %7D%0A%0A
             
@@ -1628,28 +1628,24 @@
             
-    
 settingsDao.
@@ -1653,30 +1653,16 @@
 ave(s);%0A
-            %7D%0A
         

update settings also