package eu.dnetlib.openaire.usermanagement.utils;

import com.google.gson.JsonParser;
import eu.dnetlib.openaire.usermanagement.api.Test3Service;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
import org.springframework.beans.factory.annotation.Value;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class AuthenticationUtils {

    @Value("${oidc.issuer}")
    private String issuer;

    @Value("${oidc.secret}")
    private String secret;

    @Value("${oidc.id}")
    private String id;

    private Logger logger = Logger.getLogger(AuthenticationUtils.class);

    public static boolean isAuthenticated(OIDCAuthenticationToken authenticationToken) {
        if (authenticationToken != null) {
            return true;
        }
        return false;
    }

    public static boolean hasJWTExpired(String accessToken){
        String regex = "^([A-Za-z0-9-_=]+)\\.([A-Za-z0-9-_=]+)\\.?([A-Za-z0-9-_.+=]*)$";
        Matcher matcher = Pattern.compile(regex).matcher(accessToken);

        long exp = new JsonParser().parse(new String(Base64.getDecoder().decode(matcher.group(2)))).getAsJsonObject().get("exp").getAsLong();
        return (exp - (new Date().getTime()/1000)<=0);
    }

    /*
    public void refreshAccessToken(String refreshToken) {
        //TODO fix this
        if (refreshToken == null || refreshToken.isEmpty()) {
            return;
        }

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httppost = new HttpPost(issuer+"/token");

        // Request parameters and other properties.
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("client_id", id));
        params.add(new BasicNameValuePair("client_secret", secret));
        params.add(new BasicNameValuePair("grant_type", "refresh_token"));
        params.add(new BasicNameValuePair("refresh_token", refreshToken));
        params.add(new BasicNameValuePair("scope", "openid"));

        HttpResponse response = null;

        try {
            httppost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
            //Execute and get the response.
            response = httpclient.execute(httppost);
            org.apache.http.HttpEntity entity = response.getEntity();

            //TODO fix this
            if (response.getStatusLine().getStatusCode() == 401) {
                return;
            }

            String serverMessage = IOUtils.toString(entity.getContent(), StandardCharsets.UTF_8.name());

        }  catch (UnsupportedEncodingException uee) {
            logger.error(uee);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(String.format(, 500, "Fail to get access token.", uee.getMessage()))
                    .type(MediaType.APPLICATION_JSON).build();

        } catch (IOException ioe) {
            logger.error(ioe);
            return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(String.format(, 500, "Fail to get access token.", ioe.getMessage()))
                    .type(MediaType.APPLICATION_JSON).build();

        }
    }*/
}
