package org.wso2.carbon.device.mgt.ios.core.impl;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.device.mgt.ios.core.exception.IOSEnrollmentException;
import org.wso2.carbon.device.mgt.ios.core.util.AppConfigurations;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

public class KeyStoreReader {

    private static final Log log = LogFactory.getLog(KeyStoreReader.class);

    private KeyStore loadKeyStore(String configEntryKeyStoreType, String configEntryKeyStorePath,
                                  String configEntryKeyStorePassword) throws IOSEnrollmentException {

        InputStream inputStream = null;
        KeyStore keystore;

        try {
            keystore = KeyStore.getInstance(AppConfigurations.getConfigEntry(configEntryKeyStoreType));
            inputStream = new FileInputStream(AppConfigurations.getConfigEntry(configEntryKeyStorePath));
            keystore.load(inputStream, AppConfigurations.getConfigEntry(configEntryKeyStorePassword).toCharArray());

        } catch (KeyStoreException e) {
            String errorMsg = "KeyStore issue occurred when loading KeyStore";
            log.error(errorMsg, e);
            throw new IOSEnrollmentException(errorMsg, e);
        } catch (FileNotFoundException e) {
            String errorMsg = "KeyStore file not found when loading KeyStore";
            log.error(errorMsg, e);
            throw new IOSEnrollmentException(errorMsg, e);
        } catch (NoSuchAlgorithmException e) {
            String errorMsg = "Algorithm not found when loading KeyStore";
            log.error(errorMsg, e);
            throw new IOSEnrollmentException(errorMsg, e);
        } catch (CertificateException e) {
            String errorMsg = "Certificate expired when loading KeyStore";
            log.error(errorMsg, e);
            throw new IOSEnrollmentException(errorMsg, e);
        } catch (IOException e) {
            String errorMsg = "Input output issue occurred when loading KeyStore";
            log.error(errorMsg, e);
            throw new IOSEnrollmentException(errorMsg, e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                log.error("Error closing KeyStore input stream", e);
            }
        }

        return keystore;
    }

    KeyStore loadCarbonKeyStore() throws IOSEnrollmentException {
        return loadKeyStore(AppConfigurations.KEYSTORE, AppConfigurations.PATH_KEYSTORE,
                AppConfigurations.KEYSTORE_PASSWORD);
    }
}
