package com.amazonaws.service.apigateway.importer.config;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.Optional;

public class AwsConfig {
    private static final Log LOG = LogFactory.getLog(AwsConfig.class);
    public static final String DEFAULT_REGION = "us-east-1";

    private String region;
    private String profile;

    public AwsConfig(String profile) {
        this.profile = profile;
    }

    public String getRegion() {
        return region;
    }

    public String getProfile() {
        return profile;
    }

    public void load() {
        Optional<String> region = loadRegion();

        if (region.isPresent()) {
            this.region = region.get();
        } else {
            this.region = DEFAULT_REGION;
            LOG.warn("Could not load region configuration. Please ensure AWS CLI is " +
                             "configured via 'aws configure'. Will use default region of " + this.region);
        }
    }

    private Optional<String> loadRegion() {
        String file = System.getProperty("user.home") + "/.aws/config";

        boolean foundProfile = false;
        try (BufferedReader br = new BufferedReader(new FileReader(new File(file)))) {
            String line;
            while ((line = br.readLine()) != null) {

                if (line.startsWith("[") && line.contains(this.profile)) {
                    foundProfile = true;
                }

                if (foundProfile && line.startsWith("region")) {
                    return Optional.of(line.substring(7, line.length()));
                }
            }
        } catch (Throwable t) {
            throw new RuntimeException("Could not load configuration. Please run 'aws configure'");
        }

        return Optional.empty();
    }

}

@@ -243,16 +243,42 @@
 ptional;
+%0Aimport java.util.regex.*;
 %0A%0Apublic
@@ -1375,16 +1375,155 @@
 g line;%0A
+            String region;%0A            Pattern regionPat = Pattern.compile(%22%5Ba-z%5D%7B2%7D+-%5Ba-z%5D%7B2,%7D+-%5B0-9%5D%22); %0A            Matcher regionMat;%0A%0A
         
@@ -1567,16 +1567,16 @@
 null) %7B%0A
-
 %0A       
@@ -1794,25 +1794,15 @@
   re
-turn Optional.of(
+gion = 
 line
@@ -1816,9 +1816,9 @@
 ing(
-7
+9
 , li
@@ -1829,16 +1829,408 @@
 ength())
+;%0A                    regionMat = regionPat.matcher(region);%0A                    if (! regionMat.matches()) %7B%0A                        LOG.error(%22Region does not match '%5Ba-z%5D%7B2%7D+-%5Ba-z%5D%7B2,%7D+-%5B0-9%5D': %22 + region);%0A                        throw new RuntimeException(%22Region does not match '%5Ba-z%5D%7B2%7D+-%5Ba-z%5D%7B2,%7D+-%5B0-9%5D'%22 + region);%0A                    %7D%0A                    return Optional.of(region
 );%0A     

Throw error if the parsed region does not match [a-z]{2}+-[a-z]{2,}+-[0-9] (issue #45)