package eu.dnetlib.openaire.usermanagement;

import com.google.gson.Gson;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.log4j.Logger;
import org.mitre.openid.connect.client.service.impl.StaticClientConfigurationService;
import org.mitre.openid.connect.model.OIDCAuthenticationToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class PersonalTokenServlet extends HttpServlet {

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

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

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

    @Autowired
    private StaticClientConfigurationService staticClientConfigurationService;

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

    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
                config.getServletContext());
    }

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        StringBuilder name = new StringBuilder().append(authentication.getUserInfo().getGivenName().charAt(0));
        name.append(authentication.getUserInfo().getFamilyName().charAt(0));
        request.getSession().setAttribute("name", name.toString());
        request.getSession().setAttribute("accessToken", authentication.getAccessTokenValue());
        request.getSession().setAttribute("refreshToken", authentication.getRefreshTokenValue());
        request.getRequestDispatcher("./personal.jsp").include(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        OIDCAuthenticationToken authentication = (OIDCAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        String refreshToken = authentication.getRefreshTokenValue();
        List<String> oldRefreshTokens = null;

        try {
            oldRefreshTokens = getOldRefreshTokens(authentication.getRefreshTokenValue(), authentication.getAccessTokenValue());
            deleteOldRefreshTokens(oldRefreshTokens, authentication.getAccessTokenValue());

        } catch (IOException e) {
            logger.error("Error deleting old refresh tokens.", e);
            //TODO should I let user know?
        }
        request.getSession().setAttribute("showRefreshToken", true);
        response.sendRedirect("./personalToken");
    }

    private void deleteOldRefreshTokens(List<String> oldRefreshTokens, String accessToken) throws IOException {
        HttpDelete httpDelete;
        CloseableHttpClient httpclient = HttpClients.createDefault();

        for (String refreshTokenId:oldRefreshTokens) {
            httpDelete = new HttpDelete(issuer + "/api/tokens/refresh/" + refreshTokenId);
            httpDelete.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
            HttpResponse response = httpclient.execute(httpDelete);
            if (response.getStatusLine().getStatusCode()!=200) {
                logger.warn("Could not delete old refresh tokens." + response.getStatusLine().getStatusCode());
                //System.out.println("Could not delete old refresh tokens." + response.getStatusLine().getStatusCode());//TODO should I throw exception?
            }
        }
    }

    private List<String> getOldRefreshTokens(String currentRefreshToken, String accessToken) throws IOException {
        HttpGet httpGet = new HttpGet(issuer + "/api/tokens/refresh");
        httpGet.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);

        CloseableHttpClient httpclient = HttpClients.createDefault();
        String jsonResponse = IOUtils.toString(httpclient.execute(httpGet).getEntity().getContent(), StandardCharsets.UTF_8.name());
        Gson gson = new Gson();

        List<String> oldRefreshTokens = null;
        for(RefreshToken refreshToken:gson.fromJson(jsonResponse, RefreshToken[].class)){
            if (oldRefreshTokens == null) {
                oldRefreshTokens = new ArrayList<>();
            }

            if (!refreshToken.getValue().equals(currentRefreshToken)) {
                oldRefreshTokens.add(refreshToken.getId()+"");
            }
        }

        return oldRefreshTokens;
    }
}