package com.flowci.core.common.service;

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

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

@Service
public class SettingServiceImpl implements SettingService {

    @Autowired
    private ServerProperties serverProperties;

    @Autowired
    private SettingsDao settingsDao;

    @PostConstruct
    public void setDefaultValue() {
        Optional<Settings> optional = settingsDao.findById(Settings.DefaultId);
        if (!optional.isPresent()) {
            String address = serverProperties.getAddress().toString().replace("/", "");
            Settings s = new Settings();
            s.setServerUrl(String.format("http://%s:%s", address, serverProperties.getPort()));
            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);
    }
}

@@ -128,16 +128,101 @@
 ttings;%0A
+import com.flowci.core.common.domain.Variables;%0Aimport com.flowci.util.StringHelper;%0A
 import o
@@ -645,16 +645,149 @@
 gsDao;%0A%0A
+    /**%0A     * Set default server url%0A     * value from FLOWCI_SERVER_URL or http://FLOWCI_SERVER_ADDRESS:FLOWCI_SERVER_PORT%0A     */%0A
     @Pos
@@ -946,24 +946,153 @@
 resent()) %7B%0A
+            String serverUrl = System.getenv(Variables.App.ServerUrl);%0A%0A            if (!StringHelper.hasValue(serverUrl)) %7B%0A    
             
@@ -1183,63 +1183,21 @@
     
-Settings s = new Settings();%0A            s.setS
+    s
 erverUrl
 (Str
@@ -1192,17 +1192,19 @@
 erverUrl
-(
+ = 
 String.f
@@ -1261,16 +1261,110 @@
 tPort())
+;%0A            %7D%0A%0A            Settings s = new Settings();%0A            s.setServerUrl(serverUrl
 );%0A     

load defalut server url from env first