package kr.co.icontrols.ilp300_700.ethernet;

import android.util.Log;

import java.io.InputStream;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;

public class SSLServer {

    String TAG = "SSLServer";

    private SSLServerSocket mSSLServerSocket = null;

    /**
     * SSL Server Socket 을 생성한다.
     *
     * @param nPort     - 생성된 소켓이 수신하여야 하는 포트
     * @param KeyStream - 인증키 리소스
     * @param KeyPass   - 인증키 비밀번호
     *                  <p>
     *                  <br><br>
     * @Example <pre class="prettyprint">
     * // SslServer 정의
     * SslServer sslServer = new SslServer(10000, getResources().openRawResource(R.raw.wallpad_key), "password");
     * SSLServerSocket sslServersocket = sslServer.getServerSocket();
     * <p>
     * // 서버 수신 대기
     * Socket socket = sslServersocket.accept();
     * </pre>
     */
    public SSLServer(int nPort, InputStream KeyStream, String KeyPass) {
        try {
            // 1. Param check
            if (KeyStream == null) {
                Log.w(TAG, "[SSLServer] KeyStream is null!!");
                return;
            }

            if (KeyPass == null) {
                Log.w(TAG, "[SSLServer] KeyPass is null!!");
                return;
            }

            // 2. make tls server socket
            char[] KeyPhrase = KeyPass.toCharArray();
            KeyStore mKeyStore = KeyStore.getInstance("BKS");

            mKeyStore.load(KeyStream, KeyPhrase);
            KeyManagerFactory mKeyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            mKeyManagerFactory.init(mKeyStore, KeyPhrase);

            SSLContext mSSLContext = SSLContext.getInstance("TLS");
            mSSLContext.init(mKeyManagerFactory.getKeyManagers(), null, null);

            mSSLServerSocket = (SSLServerSocket) mSSLContext.getServerSocketFactory().createServerSocket(nPort);

        } catch (Exception e) {
            Log.e(TAG, "[Exception] SSLServer(int nPort, InputStream KeyStream, String KeyPass)");
            e.printStackTrace();
        }
    }

    /**
     * 생성된 SSL Server Socket 을 반환한다.
     *
     * @return (SSLServerSocket) sslServerSocket
     */
    public SSLServerSocket getSSLServerSocket() {
        return mSSLServerSocket;
    }

    public void checkSSLServer() {
        try {
            if (mSSLServerSocket == null)
                Log.i(TAG, "[checkSSLServer] mSSLServerSocket is null!!]");
            else Log.i(TAG, "[checkSSLServer] mSSLServerSocket is not null!!]");
            Log.i(TAG, "[checkSSLServer] mSSLServerSocket.isClosed() [" + mSSLServerSocket.isClosed() + "]");
            Log.i(TAG, "[checkSSLServer] mSSLServerSocket.isBound() [" + mSSLServerSocket.isBound() + "]");
        } catch (Exception e) {
            Log.e(TAG, "[Exception] closeSSLServerSocket()");
            e.printStackTrace();
        }
    }


}