package io.trustbuilder.mfa.android.demoapp.user_api;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonPrimitive;
import com.google.gson.JsonSerializer;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Base64;

import io.tb.userapi.api.MfaSecureTokensSelfManagementApi;
import io.tb.userapi.invoker.JSON;
import okhttp3.OkHttpClient;

public class UserClient {
    final MfaSecureTokensSelfManagementApi secureTokensApi = new MfaSecureTokensSelfManagementApi(new UserApiClient());

    public UserClient(String baseUrl, OkHttpClient httpClient, String jwt) {
        Gson gson = new GsonBuilder()
                .registerTypeAdapter(LocalDateTime.class, (JsonDeserializer<LocalDateTime>) (json, type, jsonDeserializationContext) -> {
                    try {
                        return LocalDateTime.parse(json.getAsJsonPrimitive().getAsString(), DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"));
                    } catch (DateTimeParseException e) {
                        try {
                            return LocalDateTime.parse(json.getAsJsonPrimitive().getAsString(), DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'"));
                        } catch (DateTimeParseException a) {
                            return LocalDateTime.parse(json.getAsJsonPrimitive().getAsString(), DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSXXXXX"));
                        }
                    }
                })
                .registerTypeAdapter(byte[].class, (JsonSerializer<byte[]>) (src, typeOfSrc, context) -> new JsonPrimitive(Base64.getEncoder().encodeToString(src)))
                .registerTypeAdapter(byte[].class, (JsonDeserializer<byte[]>) (json, typeOfT, context) -> Base64.getDecoder().decode(json.getAsString()))
                .create();
        JSON json = new JSON();
        json.setGson(gson);
        secureTokensApi.getApiClient().setJSON(json);
        secureTokensApi.getApiClient().setBasePath(baseUrl);
        secureTokensApi.getApiClient().setHttpClient(httpClient);
        if (jwt != null) {
            secureTokensApi.getApiClient().addDefaultHeader("Authorization", "Bearer " + jwt);
        }
    }
}