package com.hclsoftware.sso.kerberos.service;

import com.hclsoftware.sso.kerberos.dto.ResponseDto;
import com.hclsoftware.sso.kerberos.utils.Serializer;
import com.ibm.as400.access.*;
import com.ibm.as400.security.auth.ProfileTokenCredential;
import org.ietf.jgss.GSSCredential;
import org.ietf.jgss.GSSException;
import org.ietf.jgss.GSSManager;
import org.ietf.jgss.Oid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.kerberos.authentication.JaasSubjectHolder;
import org.springframework.security.kerberos.authentication.KerberosUsernamePasswordAuthenticationToken;
import org.springframework.security.kerberos.authentication.sun.SunJaasKerberosTicketValidator;
import org.springframework.stereotype.Service;

import javax.security.auth.Subject;
import javax.security.auth.kerberos.KerberosTicket;
import javax.security.auth.login.LoginException;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.util.Base64;
import java.util.Optional;
import java.util.Set;

@Service
public class IBMiConnectorService {


    @Value("${app.service-principal}")
    private String servicePrincipal;

    @Value("${app.keytab-location}")
    private String keytabLocation;

    @Value("${app.as400Host}")
    private String as400Host;

    @Autowired
    private SunJaasKerberosTicketValidator ticketValidator;


    public ProfileTokenCredential ibmIMc() throws PropertyVetoException, GSSException, LoginException, IOException {

        ProfileTokenCredential profileTokenCredential = null;

        GSSCredential gssCredential = getGssCredential();

        System.setProperty("com.ibm.as400.access.Trace.enabled", "true");
        AS400 as400 = new AS400(as400Host);
        System.out.println("as400.getGSSName() : "+as400.getGSSName());

        as400.setGSSCredential(gssCredential);

        try {
            profileTokenCredential = as400.getProfileToken();
            //profileTokenCredential.setTokenType(ProfileTokenCredential.TYPE_MULTIPLE_USE_RENEWABLE);


        } catch (/*PropertyVetoException |*/ AS400SecurityException | IOException | InterruptedException e) {
            System.err.println(":: Exception ::" + e.toString());
            e.printStackTrace();
        } finally {
            try {
                // Make sure to disconnect
                if (as400 != null) {
                    as400.disconnectAllServices();
                }
            } catch (Exception e) {
                System.err.println(":: Exception ::" + e.toString());
            }
        }
        return profileTokenCredential;

    }

    public GSSCredential getGssCredential() throws GSSException {
        Authentication existingAuth = SecurityContextHolder.getContext().getAuthentication();

        Oid krb5MechOid = new Oid("1.2.840.113554.1.2.2");
        //Oid spnegoMechOid = new Oid("1.3.6.1.5.5.2");

        KerberosUsernamePasswordAuthenticationToken existingAuth1 = (KerberosUsernamePasswordAuthenticationToken) existingAuth;

        JaasSubjectHolder jaasSubjectHolder = existingAuth1.getJaasSubjectHolder();
        Subject jaasSubject = jaasSubjectHolder.getJaasSubject();
        Set<Object> privateCredentials = jaasSubject.getPrivateCredentials();


        Optional<KerberosTicket> OptionalClientGssCreds = privateCredentials.stream()
                .filter(privateCredential ->
                        privateCredential instanceof KerberosTicket).map(privateCredential -> (KerberosTicket) privateCredential).findFirst();
        KerberosTicket kerberosTicket = OptionalClientGssCreds.get();

        GSSCredential gssCredential = Subject.doAs(jaasSubject, (PrivilegedAction<GSSCredential>) () -> {
            try {
                // Obtain GSSCredential from the Subject
                return Subject.doAs(jaasSubject, (PrivilegedExceptionAction<GSSCredential>) () ->
                        GSSManager.getInstance().createCredential(null, GSSCredential.INDEFINITE_LIFETIME,
                                krb5MechOid, GSSCredential.INITIATE_ONLY));
            } catch (Exception e) {
                // Handle exception
                e.printStackTrace();
                return null;
            }
        });
        return gssCredential;
    }



    /*for testing need to remove if doesn't work*/

    public AS400 getAs400() throws GSSException {

        System.out.println("from getAs400 ");
        GSSCredential gssCredential = getGssCredential();

        System.setProperty("com.ibm.as400.access.Trace.enabled", "true");
        AS400 as400 = new AS400(as400Host);
        System.out.println("as400.getGSSName() : "+as400.getGSSName());

        as400.setGSSCredential(gssCredential);


        return as400;

    }

    public ResponseDto getResponseDtoForIbmIMc() throws GSSException, IOException {

        ProfileTokenCredential profileTokenCredential = null;

        GSSCredential gssCredential = getGssCredential();

        System.setProperty("com.ibm.as400.access.Trace.enabled", "true");
        AS400 as400 = new AS400(as400Host);


        as400.setGSSCredential(gssCredential);
        System.out.println("as400.getUserId() : "+as400.getUserId());

        try {
            profileTokenCredential = as400.getProfileToken();
            //profileTokenCredential.setTokenType(ProfileTokenCredential.TYPE_MULTIPLE_USE_RENEWABLE);


        } catch (/*PropertyVetoException |*/ AS400SecurityException | IOException | InterruptedException e) {
            System.err.println(":: Exception ::" + e.toString());
            e.printStackTrace();
        } finally {
            try {
                // Make sure to disconnect
                if (as400 != null) {
                    as400.disconnectAllServices();
                }
            } catch (Exception e) {
                System.err.println(":: Exception ::" + e.toString());
            }
        }
        byte[] serialize = Serializer.serialize(profileTokenCredential);//SerializationUtils.serialize(gssCredential);
        String token = Base64.getEncoder().encodeToString(serialize);
        return new ResponseDto(as400Host, as400.getUserId(), token);

    }
}
