package kr.co.icontrols.ilp300_700.ethernet;

import android.util.Log;

import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

import kr.co.icontrols.ilp300_700.global.Configure.ConfigValue;
import kr.co.icontrols.ilp300_700.global.Configure.SetValue;

public class SendMSG extends Thread {

    String TAG = "SendMSG";

    boolean bLOG = true;   // true, false
    boolean bLOG_DEBUG = false;   // true, false
    boolean bLOG_INFO = true;   // true, false
    String strSendMSG;
    String strTargetIP;
    int nTargetPort;

    public SendMSG(String Msg, String TargetIP, int TargetPort) {
        strSendMSG = Msg;
        strTargetIP = TargetIP;
        nTargetPort = TargetPort;

        LOG("[SendMSG] Message destination [" + strTargetIP + ":" + nTargetPort + "]");
        Log.i(TAG, "[SendMSG] ConfigValue.eMainServerType [" + ConfigValue.eMainServerType + "]");
        Log.d(TAG, "[SendMSG] ========== iMAP Start ==========\r\n" + strSendMSG + "\r\n[SendMSG] ========== iMAP End ==========");
    }

    private void LOG(String log) {
        if (bLOG) Log.v(TAG, log);
    }

    private void LOG_DEBUG(String log) {
        if (bLOG_DEBUG) Log.d(TAG, log);
    }

    private void LOG_INFO(String log) {
        if (bLOG_INFO) Log.i(TAG, log);
    }

    public void run() {
        Socket SendSock;
        try {
            if (ConfigValue.eMainServerType == SetValue.Server2dot0_Integrated) {
                // 암호화
                SSLClient mSSLClientSocket = new SSLClient(strTargetIP, nTargetPort);
                SendSock = mSSLClientSocket.getSocket();
                SendSock.setSoLinger(true, 1000);
                DataOutputStream OutStm = new DataOutputStream(SendSock.getOutputStream());
                byte[] OutBuffer = strSendMSG.getBytes("euc-kr");
                OutStm.write(OutBuffer);
                OutStm.flush();
                SendSock.setSoLinger(true, 1000);
                SendSock.close();
            } else {
                // 비암호화
                SendSock = new Socket(strTargetIP, nTargetPort);
                SendSock.setSoLinger(true, 1000);
                DataOutputStream OutStm = new DataOutputStream(SendSock.getOutputStream());
                byte[] OutBuffer = strSendMSG.getBytes("euc-kr");
                OutStm.write(OutBuffer);
                OutStm.flush();
                SendSock.setSoLinger(true, 1000);
                SendSock.close();
            }
        } catch (UnknownHostException e) {
            Log.e(TAG, "[UnknownHostException] SendMSG.run()");
            e.printStackTrace();
        } catch (IOException e) {
            Log.e(TAG, "[IOException] SendMSG.run()");
            e.printStackTrace();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] SendMSendMSG.run()");
            e.printStackTrace();
        }
    }
}