package com.github.nomensvyat.switchbox.parser;


import com.github.nomensvyat.switchbox.FieldMap;
import com.google.gson.Gson;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class FieldMapLoader {

    private final Gson gson;
    private FieldMap cachedFieldMap;
    private long cacheTimestamp;

    private FieldMapLoader() {
        gson = GsonFabric.create();
    }

    private static FieldMapLoader getInstance() {
        return InstanceHolder.INSTANCE;
    }

    public static FieldMap load(File file) {
        return getInstance().loadInternal(file);
    }

    public static boolean needToLoad(File file) {
        return getInstance().needToLoadInternal(file);
    }

    private boolean needToLoadInternal(File file) {
        return !(cacheTimestamp == file.lastModified() && cachedFieldMap != null);
    }

    private FieldMap loadInternal(File file) {
        checkFile(file);

        FileReader fileReader;
        try {
            fileReader = new FileReader(file);
        } catch (FileNotFoundException e) {
            throw new IllegalArgumentException("File not found", e);
        }

        cachedFieldMap = gson.fromJson(fileReader, FieldMap.class);
        cacheTimestamp = file.lastModified();

        return cachedFieldMap;
    }

    private void checkFile(File file) {
        if (!file.exists()) {
            throw new IllegalArgumentException("File " + file.getAbsolutePath() + " not found");
        }
    }

    private static class InstanceHolder {
        private static FieldMapLoader INSTANCE = new FieldMapLoader();
    }
}

@@ -120,16 +120,112 @@
 on.Gson;
+%0Aimport com.google.gson.JsonParseException;%0A%0Aimport org.gradle.api.tasks.StopExecutionException;
 %0A%0Aimport
@@ -303,16 +303,44 @@
 eReader;
+%0Aimport java.io.IOException;
 %0A%0Apublic
@@ -1071,16 +1071,21 @@
         
+try (
 FileRead
@@ -1101,68 +1101,104 @@
 ader
-;%0A        try %7B%0A            fileReader = new FileReader(file
+ = new FileReader(file)) %7B%0A            cachedFieldMap = gson.fromJson(fileReader, FieldMap.class
 );%0A 
@@ -1265,32 +1265,29 @@
  new Illegal
-Argument
+State
 Exception(%22F
@@ -1315,25 +1315,115 @@
        %7D
-%0A
+ catch (IOException e) %7B%0A            throw new IllegalStateException(%22Can't read file%22, e);
 %0A       
  cachedF
@@ -1418,68 +1418,311 @@
     
+ %7D
  ca
+t
 ch
-edFieldMap = gson.fromJson(fileReader, FieldMap.class);
+ (JsonParseException e) %7B%0A            StopExecutionException stopExecutionException = new StopExecutionException(%0A                    %22Can't parse fields from file: %22 + file.getAbsolutePath());%0A            stopExecutionException.initCause(e);%0A            throw stopExecutionException;%0A        %7D%0A
 %0A   

Throw exception on parse error