package inji.utils;

import com.github.javafaker.Faker;
import io.mosip.testrig.apirig.dto.TestCaseDTO;
import io.mosip.testrig.apirig.utils.*;
import io.restassured.response.Response;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.testng.SkipException;

import javax.ws.rs.core.MediaType;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class InjiWalletUtil extends AdminTestUtil {

    private static final Logger logger = Logger.getLogger(InjiWalletUtil.class);
    private static final AdminTestUtil adminTestUtil = new AdminTestUtil();
    private static final Faker faker = new Faker();
//    private static final String fullNameForSunBirdR = generateFullNameForSunBirdR();
//    private static final String dobForSunBirdR = generateDobForSunBirdR();
    private static final String dobForSunBirdR = String.valueOf(LocalDate.now());
//    private static final String policyNumberForSunBirdR = generateRandomNumberString(9);

    public static void setLogLevel() {
        if (InjiWalletConfigManager.IsDebugEnabled())
            logger.setLevel(Level.ALL);
        else
            logger.setLevel(Level.ERROR);
    }

    public static TestCaseDTO isTestCaseValidForTheExecution(TestCaseDTO testCaseDTO) {
        String testCaseName = testCaseDTO.getTestCaseName();

        int indexof = testCaseName.indexOf("_");
        String modifiedTestCaseName = testCaseName.substring(indexof + 1);

        addTestCaseDetailsToMap(modifiedTestCaseName, testCaseDTO.getUniqueIdentifier());


        String endpoint = testCaseDTO.getEndPoint();
        String inputJson = testCaseDTO.getInput();


        if (SkipTestCaseHandler.isTestCaseInSkippedList(testCaseName)) {
            throw new SkipException(GlobalConstants.KNOWN_ISSUES);
        }
        return testCaseDTO;
    }

    public static String inputstringKeyWordHandeler(String jsonString, String testCaseName) {

        if (jsonString.contains(GlobalConstants.TIMESTAMP)) {
            jsonString = replaceKeywordWithValue(jsonString, GlobalConstants.TIMESTAMP, generateCurrentUTCTimeStamp());
        }

        if (jsonString.contains("$POLICYNUMBERFORSUNBIRDRC$")) {
            String policyNumberForSunBirdR = generateRandomNumberString(9);
            jsonString = replaceKeywordWithValue(jsonString, "$POLICYNUMBERFORSUNBIRDRC$", policyNumberForSunBirdR);
            adminTestUtil.writeAutoGeneratedId(testCaseName, "POLICY", policyNumberForSunBirdR);
        }

        if (jsonString.contains("$FULLNAMEFORSUNBIRDRC$")) {
            String fullNameForSunBirdR = generateFullNameForSunBirdR();
            jsonString = replaceKeywordWithValue(jsonString, "$FULLNAMEFORSUNBIRDRC$", fullNameForSunBirdR);
            adminTestUtil.writeAutoGeneratedId(testCaseName, "NAME", fullNameForSunBirdR);
        }

        if (jsonString.contains("$DOBFORSUNBIRDRC$")) {
            jsonString = replaceKeywordWithValue(jsonString, "$DOBFORSUNBIRDRC$", dobForSunBirdR);
            adminTestUtil.writeAutoGeneratedId(testCaseName, "DOB", dobForSunBirdR);
        }

        return jsonString;

    }

    public static String generateFullNameForSunBirdR() {
        return faker.name().fullName();
    }

    public static String generateDobForSunBirdR() {
        Faker faker = new Faker();
        LocalDate dob = faker.date().birthday().toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDate();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        return dob.format(formatter);
    }

    public static JSONArray mimotoActuatorResponseArray = null;

    public static String getValueFromMimotoActuator(String section, String key) {
        String url = ApplnURI + ConfigManager.getproperty("actuator_mimoto_endpoint");
        if (!(System.getenv("useOldContextURL") == null)
                && !(System.getenv("useOldContextURL").isBlank())
                && System.getenv("useOldContextURL").equalsIgnoreCase("true")) {
            if (url.contains("/v1/mimoto/")) {
                url = url.replace("/v1/mimoto/", "/residentmobileapp/");
            }
        }
        String actuatorCacheKey = url + section + key;
        String value = actuatorValueCache.get(actuatorCacheKey);
        if (value != null && !value.isEmpty())
            return value;

        try {
            if (mimotoActuatorResponseArray == null) {
                Response response = null;
                JSONObject responseJson = null;
                response = RestClient.getRequest(url, MediaType.APPLICATION_JSON, MediaType.APPLICATION_JSON);

                responseJson = new JSONObject(response.getBody().asString());
                mimotoActuatorResponseArray = responseJson.getJSONArray("propertySources");
            }
            for (int i = 0, size = mimotoActuatorResponseArray.length(); i < size; i++) {
                JSONObject eachJson = mimotoActuatorResponseArray.getJSONObject(i);
                if (eachJson.get("name").toString().contains(section)) {
                    value = eachJson.getJSONObject(GlobalConstants.PROPERTIES).getJSONObject(key)
                            .get(GlobalConstants.VALUE).toString();
                    if (ConfigManager.IsDebugEnabled())
                        logger.info("Actuator: " + url + " key: " + key + " value: " + value);
                    break;
                }
            }
            actuatorValueCache.put(actuatorCacheKey, value);

            return value;
        } catch (Exception e) {

            return "";
        }
    }

    public static String getOtp() {
        String otp = "111111";
        return otp;
    }
}