package org.jetbrains.haskell.config;

import com.intellij.openapi.components.*;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.haskell.util.OsUtil;
import org.jetbrains.haskell.util.UtilPackage;

import java.io.File;

@State(
        name = "HaskellConfiguration",
        storages = {
                @Storage(id = "default", file = StoragePathMacros.APP_CONFIG + "/haskell.xml")
        }
)
public class HaskellSettings implements PersistentStateComponent<HaskellSettings.State> {

    @NotNull
    public static HaskellSettings getInstance() {
        HaskellSettings persisted = ServiceManager.getService(HaskellSettings.class);
        if (persisted == null) {
            persisted = new HaskellSettings();
        }

        persisted.update();

        return persisted;
    }

    public static class State {
        public String ghcModPath;
        public String ghcModiPath;
        public String buildWrapperPath;
        public String scionBrowserPath;
        public String cabalPath;
        public String cabalDataPath;
    }

    State myState = new State();

    void update() {
        if (myState.cabalPath == null) {
            myState.cabalPath = "cabal";
        }

        if (myState.cabalDataPath == null) {
            OsUtil os = UtilPackage.getOS();
            myState.cabalDataPath = os.getCabalData();
        }

        if (myState.ghcModPath == null) {
            OsUtil os = UtilPackage.getOS();
            myState.ghcModPath = os.getDefaultCabalBin() + File.separator + "ghc-mod" + os.getExe();
        }

        if (myState.ghcModiPath == null) {
            OsUtil os = UtilPackage.getOS();
            myState.ghcModiPath = os.getDefaultCabalBin() + File.separator + "ghc-modi" + os.getExe();
        }

        if (myState.buildWrapperPath == null) {
            OsUtil os = UtilPackage.getOS();
            myState.buildWrapperPath = os.getDefaultCabalBin() + File.separator + "buildwrapper" + os.getExe();
        }

        if (myState.scionBrowserPath == null) {
            OsUtil os = UtilPackage.getOS();
            myState.scionBrowserPath = os.getDefaultCabalBin() + File.separator + "scion-browser" + os.getExe();
        }

    }

    @NotNull
    public State getState() {
        return myState;
    }

    public void loadState(State state) {
        myState = state;
        update();
    }

}

@@ -494,16 +494,72 @@
 ate%3E %7B%0A%0A
+    public HaskellSettings() %7B%0A        update();%0A    %7D%0A%0A
     @Not
@@ -744,27 +744,22 @@
         
-persisted =
+return
  new Has
@@ -788,38 +788,8 @@
   %7D%0A
-%0A        persisted.update();%0A%0A
     
@@ -2207,25 +2207,24 @@
 ;%0A        %7D%0A
-%0A
     %7D%0A%0A    @

Fix NPE #32