package kr.co.icontrols.ilp300_700.screen;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils.TruncateAt;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.RelativeLayout;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

import cm.sip.hns.SIPSound;
import kr.co.icontrols.ilp300_700.MainActivity;
import kr.co.icontrols.ilp300_700.MainActivity.HANDLERMSG;
import kr.co.icontrols.ilp300_700.MainActivity.TTSEventListener;
import kr.co.icontrols.ilp300_700.R;
import kr.co.icontrols.ilp300_700.call.CallController.CallEventListener;
import kr.co.icontrols.ilp300_700.call.CallManager.CALLPATH;
import kr.co.icontrols.ilp300_700.call.CallManager.CALLSTATUS;
import kr.co.icontrols.ilp300_700.call.CallManager.CALLTYPE;
import kr.co.icontrols.ilp300_700.call.CallManager.CHATEVENT;
import kr.co.icontrols.ilp300_700.call.CallManager.REMOTECALLOWNER;
import kr.co.icontrols.ilp300_700.ethernet.EthernetCtrl;
import kr.co.icontrols.ilp300_700.ethernet.iMAPCommon.iMAPResult;
import kr.co.icontrols.ilp300_700.global.Configure.ConfigValue;
import kr.co.icontrols.ilp300_700.global.Configure.SetValue;
import kr.co.icontrols.ilp300_700.global.DataClasses.POSITION;
import kr.co.icontrols.ilp300_700.global.DataClasses.RemoteIDInfo;
import kr.co.icontrols.ilp300_700.global.Declare;
import kr.co.icontrols.ilp300_700.global.Declare.DeviceType;
import kr.co.icontrols.ilp300_700.global.Enumeration.TARGETINFOINPUTSTEP;
import kr.co.icontrols.ilp300_700.global.Enumeration.TTSEVENT;
import kr.co.icontrols.ilp300_700.global.Global;
import kr.co.icontrols.ilp300_700.global.ID;
import kr.co.icontrols.ilp300_700.imap.Request_chat_message;
import kr.co.icontrols.ilp300_700.imap.Request_check_sip_activation;
import kr.co.icontrols.ilp300_700.imap.iMAPResultCtrl;
import kr.co.icontrols.wallpadsupport.WpadImageView;
import kr.co.icontrols.wallpadsupport.WpadScreen;
import kr.co.icontrols.wallpadsupport.WpadTextView;

public class TalkResidence extends WpadScreen implements CallEventListener, TTSEventListener {

    String TAG = "TalkResidence";

    boolean bLOG = true;   // true, false
    boolean bLOG_DEBUG = false;   // true, false
    boolean bLOG_INFO = true;   // true, false
    boolean bLOG_WARN = true;   // true, false

    WpadImageView Image_Background;
    WpadImageView Image_Residence_Dong; // "동"
    WpadImageView Image_Residence_Ho; // "호"
    WpadImageView Image_Residence;
    WpadImageView Image_Call_Anim;
    WpadTextView Text_ResidenceInfo_Dong; // 동정보
    WpadTextView Text_ResidenceInfo_Ho;   // 호정보
    WpadTextView Text_Instruction;   // 안내문구
    WpadTextView Text_ChatMessage;   // 청각장애인 모드 통화 내용

    Context mContext;

    int[] BGImages = {R.drawable.bg_black, R.drawable.bg_black_700};
    int[] ResiImages = {R.drawable.cir_residence, R.drawable.image_gener};
    int[] ResiCirImages = {R.drawable.cir_white_quarter, R.drawable.cir_white_quarter_700};
    int[] DongImages = {R.drawable.image_dong, R.drawable.image_dong_700};
    int[] HoImages = {R.drawable.image_ho, R.drawable.image_ho_700};
    int[] nFontSize_DONGHO = {73, 140};
    int[] nFontSize_DONGHO_Rent = {50, 105};
//    int nFontSize_DONGHO = 100;
    int[] nFontSize_Info = {26, 46};
    int MAXLENGTH_DONG = 4;
    int MAXLENGTH_HO = 4;
    int MINLENGTH_DONG = 3;
    int MINLENGTH_HO = 3;
    boolean bFUNCBlock = false;

    String strText_Instruction = "";
    String strText_ChatMessage = "";
    String strChatTargetIP = "";
    boolean bRcvCancel = false;
    boolean bAutoCallRun = false;
    CountDownTimer InputDelayTimer;   // 메인화면에서 급격한 조작을 방지하기 위한 타이머 (통화 종료후, 통화상태 초기화를 위한 일정 시간후 입력 받음, X초)
    boolean bInputDelay = false;

    Animation mAnimation;
    
    private Handler TalkResidenceHandler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message msg) {
            LOG_INFO("[handleMessage] AlarmHandler : what [" + msg.what + "], arg1 [" + msg.arg1 + "], arg2 [" + msg.arg2 + "]");
            switch (msg.what) {
                case TALKRESIDENCE_HD_MSG.DISPLAY_CHATMESSAGE:
                    strText_ChatMessage = (String) msg.obj;
                    displayChatMessage(strText_ChatMessage);
                    break;

                case TALKRESIDENCE_HD_MSG.START_STT:
                    ((MainActivity) mContext).startSTT();
                    break;

                case TALKRESIDENCE_HD_MSG.PLAYSOUND_STT_START:
                    MainActivity.mSound.Play_lobby(R.raw.callstart);
                    break;

                case TALKRESIDENCE_HD_MSG.PLAYSOUND_STT_END:
                    MainActivity.mSound.Play_lobby(R.raw.callend);
                    break;

                default:
                    break;
            }
        }
    };

    public TalkResidence(Context context, RelativeLayout layout) {
        super(context, layout);
        try {
            LOG("------------------ [START - TalkResidence] -------------------");

            mContext = context;
            Initialize();

            super.addBrActionFilter(Declare.PrivateBR.UPDATE_KEYDATA_TALK);
            Image_Background = new WpadImageView(context, 0, Declare.DeviceInfo.getScreenSizeFullW(ConfigValue.DEVICE_MODELTYPE), Declare.DeviceInfo.getScreenSizeFullH(ConfigValue.DEVICE_MODELTYPE), BGImages[ConfigValue.DEVICE_MODELTYPE], 0, ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.BACKGROUND);
            ViewRegistration(layout, Image_Background, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.BACKGROUND).X, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.BACKGROUND).Y);

            Text_ResidenceInfo_Dong = new WpadTextView(context, false, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.RESIDENCEINFO_DONG).W, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.RESIDENCEINFO_DONG).H, Gravity.CENTER, Color.WHITE, nFontSize_DONGHO[ConfigValue.DEVICE_MODELTYPE], false, ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.RESIDENCEINFO_DONG);
            ViewRegistration(layout, Text_ResidenceInfo_Dong, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.RESIDENCEINFO_DONG).X, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.RESIDENCEINFO_DONG).Y);

            Text_ResidenceInfo_Ho = new WpadTextView(context, false, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.RESIDENCEINFO_HO).W, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.RESIDENCEINFO_HO).H, Gravity.CENTER, Color.WHITE, nFontSize_DONGHO[ConfigValue.DEVICE_MODELTYPE], false, ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.RESIDENCEINFO_HO);
            ViewRegistration(layout, Text_ResidenceInfo_Ho, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.RESIDENCEINFO_HO).X, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.RESIDENCEINFO_HO).Y);

            Image_Residence_Dong = new WpadImageView(context, 0, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE_DONG).W, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE_DONG).H, DongImages[ConfigValue.DEVICE_MODELTYPE], 0, ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE_DONG);
            ViewRegistration(layout, Image_Residence_Dong, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE_DONG).X, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE_DONG).Y);

            Image_Residence_Ho = new WpadImageView(context, 0, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE_HO).W, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE_HO).H, HoImages[ConfigValue.DEVICE_MODELTYPE], 0, ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE_HO);
            ViewRegistration(layout, Image_Residence_Ho, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE_HO).X, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE_HO).Y);

            Text_Instruction = new WpadTextView(context, false, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.INSTRUCTION).W, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.INSTRUCTION).H, Gravity.CENTER, Color.WHITE, nFontSize_Info[ConfigValue.DEVICE_MODELTYPE], false, ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.INSTRUCTION);
            ViewRegistration(layout, Text_Instruction, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.INSTRUCTION).X, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.INSTRUCTION).Y);
            Text_Instruction.setText(strText_Instruction);

            Text_ChatMessage = new WpadTextView(context, false, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.CHATMESSAGE).W, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.CHATMESSAGE).H, Gravity.CENTER, Color.YELLOW, nFontSize_Info[ConfigValue.DEVICE_MODELTYPE], false, ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.CHATMESSAGE);
            ViewRegistration(layout, Text_ChatMessage, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.CHATMESSAGE).X, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.CHATMESSAGE).Y);
            Text_ChatMessage.setText(strText_ChatMessage);
            Text_ChatMessage.setSingleLine();
            Text_ChatMessage.setEllipsize(TruncateAt.MARQUEE);
            Text_ChatMessage.setMarqueeRepeatLimit(-1);
            
            // 애니메이션
            Image_Residence = new WpadImageView(context, 0, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE).W, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE).H, ResiImages[ConfigValue.DEVICE_MODELTYPE], 0, ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE);
            ViewRegistration(layout, Image_Residence, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE).X, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE).Y);
            Image_Residence.setVisibility(View.INVISIBLE);

            Image_Call_Anim = new WpadImageView(context, 0, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE_ANIM).W, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE_ANIM).H, ResiCirImages[ConfigValue.DEVICE_MODELTYPE], 0, ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE_ANIM);
            ViewRegistration(layout, Image_Call_Anim, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE_ANIM).X, getPosition(ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE_ANIM).Y);
            Image_Call_Anim.setVisibility(View.INVISIBLE);

            mAnimation = AnimationUtils.loadAnimation(mContext, R.anim.rotate_call);
            mAnimation.setInterpolator(AnimationUtils.loadInterpolator(mContext, android.R.anim.linear_interpolator));
            mAnimation.setDuration(MainActivity.mCallController.mCTT.CALLED * 1000);
            mAnimation.setFillAfter(false);

            updateScreen();
            checkTalkTestMode();
            ((MainActivity) mContext).setAutoScreenChange(ID.SCREENS.Main, MainActivity.nDefaultScreenTimeout);
            doAutoCall();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] TalkResidence(...) : " + e);
            e.printStackTrace();
        }
    }

    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);
    }

    private void LOG_WARN(String log) {
        if (bLOG_WARN) Log.w(TAG, log);
    }

    protected void Initialize() {
        try {
            LOG("[Initialize] ===== START =====");
            MainActivity.mCallController.setCallEventListener(this);
            if (!RemoteIDInfo.bAutoCall) RemoteIDInfo.InitVariablesforResi();
            setCallLevel();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] Initialize() : " + e);
            e.printStackTrace();
        }
    }

    private void checkTalkTestMode() {
        try {
            LOG("[checkTalkTestMode] ===== START =====");
            if (MainActivity.mCallController.bTalkTestModeEnable) {
                Text_Instruction.setTextColor(Color.GREEN);
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] Initialize() : " + e);
            e.printStackTrace();
        }
    }

    @Override
    protected void onClose() {
        try {
            LOG("------------------ [onClose - TalkResidence] -------------------");
//            setAnimation(false);


            if (mPathCheckHandler != null) {
                mPathCheckHandler.removeMessages(0);
                mPathCheckHandler.removeMessages(1);
            }
            if (mVolumeCheckHandler != null) {
                mVolumeCheckHandler.removeMessages(0);
                mVolumeCheckHandler.removeMessages(1);
            }

            if (SIPSound.mHandler != null) {
                SIPSound.mHandler.removeMessages(0);
                SIPSound.mHandler.removeMessages(1);
            }

            ((MainActivity) mContext).sendHandlerMsg(HANDLERMSG.STOP_CHATMODE, 0, 0);
            ((MainActivity) mContext).releaseTTSEventListener();
            MainActivity.mCallController.releaseCallEventListener();
            Global.TargetInputStep = TARGETINFOINPUTSTEP.DONG;
            if (!RemoteIDInfo.bAutoCall) RemoteIDInfo.InitVariables();
            MainActivity.mIOInterface.setAnalogCameraPower(false);
            Global.changeVolumeMoIPMode(CALLTYPE.NONE);
            MainActivity.mCallController.mCallInfo.setRemoteCallOwner(REMOTECALLOWNER.NONE);
            //MainActivity.mCallController.mVideoJNI.mV40IFCCD.videoSet(false);
            //MainActivity.mCallController.mVideoJNI.encoderStopOperation();
            MainActivity.m_bCallType = 0;
            ((MainActivity) mContext).ctrlVideoSurface(false);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] onClose(...) : " + e);
            e.printStackTrace();
        }
        super.onClose();
    }

    @Override
    protected void onBrReceive(Intent intent) {
        try {
            LOG("[onBrReceive] Intent : " + intent);
            if (intent.getAction().equals(Declare.PrivateBR.UPDATE_KEYDATA_TALK))
            {

                int keyCode = intent.getIntExtra("data", -1);
                LOG("[onBrReceive] Intent : " + keyCode);
                if (Declare.Button.NUMBER_00 <= keyCode && keyCode <= Declare.Button.NUMBER_09) {
                    if (Global.TargetInputStep == TARGETINFOINPUTSTEP.DONG) {
                        int nPressedNum = keyCode - 7;
                        RemoteIDInfo.strDong += nPressedNum;
                        if (RemoteIDInfo.strDong.length() > MAXLENGTH_DONG) {
                            RemoteIDInfo.strDong = RemoteIDInfo.strDong.substring(1, 5);
                        }
                    } else if (Global.TargetInputStep == TARGETINFOINPUTSTEP.HO) {
                        int nPressedNum = keyCode - 7;
                        RemoteIDInfo.strHo += nPressedNum;
                        if (RemoteIDInfo.strHo.length() > MAXLENGTH_HO) {
                            RemoteIDInfo.strHo = RemoteIDInfo.strHo.substring(1, 5);
                        }
                    }
                } else if (keyCode == Declare.Button.CALL) {
                    LOG_INFO("[onKeyDown] Declare.Button.CALL");
                    startInputDelayTimer();
                    if (bFUNCBlock) return;
                    if (Global.TargetInputStep == TARGETINFOINPUTSTEP.DONE) return;
                    Global.TargetInputStep = TARGETINFOINPUTSTEP.DONE;

                    if (MainActivity.mCallController.mCallInfo.getIDLECnt() != MainActivity.mCallController.mCallInfo.IDLECNT_MAX) {
                        MainActivity.mSound.PlayMent_lobby(R.raw.inputfail);
                        MainActivity.mCallController.mCallInfo.printCallStatus();
                        LOG("[onKeyDown] CallStatus is not idle!!");
                        super.setChangeScreen(ID.SCREENS.Main);
                        return;
                    }

                    if (MINLENGTH_DONG > RemoteIDInfo.strDong.length() || MINLENGTH_HO > RemoteIDInfo.strHo.length()) {
                        initCallVariables();
                        MainActivity.mSound.PlayMent_lobby(R.raw.retryinput);
                        updateScreen();
                        return;
                    }

                    LOG("[onKeyDown] strDong [" + RemoteIDInfo.strDong + "], strHo [" + RemoteIDInfo.strHo + "], strIP [" + RemoteIDInfo.strIP + "]");

                    if (ConfigValue.eCallLevel == SetValue.Level_Line) {
                        if (!Global.isExistResi(Integer.parseInt(RemoteIDInfo.strHo))) {
                            LOG("[onKeyDown] " + RemoteIDInfo.strHo + " ho is not exist!!");
                            initCallVariables();
                            MainActivity.mSound.PlayMent_lobby(R.raw.confirmsetting);
                            super.setChangeScreen(ID.SCREENS.Main);
                            return;
                        }
                    }

                    try {
                        if (RemoteIDInfo.bRentRoomSelected)
                            RemoteIDInfo.strIP = EthernetCtrl.makeIPAddress(DeviceType.RENTRESIDENCE, RemoteIDInfo.strDong, RemoteIDInfo.strHo);
                        else
                            RemoteIDInfo.strIP = EthernetCtrl.makeIPAddress(DeviceType.RESIDENCE, RemoteIDInfo.strDong, RemoteIDInfo.strHo);
                    } catch (Exception e) {
                        MainActivity.mSound.PlayMent_lobby(R.raw.retryinput);
                        Log.e(TAG, "[Exception] onKeyDown -> EthernetCtrl.makeIPAddress(...) : " + e);
                        e.printStackTrace();
                    }

                    if (!send_check_sip_activation_request(RemoteIDInfo.strIP)) {
                        initCallVariables();
                        MainActivity.mSound.PlayMent_lobby(R.raw.trylater);
                        super.setChangeScreen(ID.SCREENS.Main);
                    }

                    MainActivity.mCallController.mCallInfo.setCallStatus(CALLTYPE.RESIDENCE, CALLSTATUS.TRYING_CALL);
                } else if (keyCode == Declare.Button.CANCEL || keyCode == Declare.Button.TACT_CANCEL) {

                    Global.stopMelodyRepeat();
                    Global.stopMelodyRepeat();

                    Global.changeVolumeMoIPMode(CALLTYPE.NONE);
                    MainActivity.mCallController.mCallInfo.setCallStatus(CALLTYPE.RESIDENCE, CALLSTATUS.IDLE);
                    MainActivity.mCallController.setCallTimer(MainActivity.mCallController.mCTT.KILLTIMER);

                    if (MainActivity.mCallController.mCallInfo.getIDLECnt() != MainActivity.mCallController.mCallInfo.IDLECNT_MAX) {
                        if (MainActivity.mCallController.mCallInfo.getRESI() == CALLSTATUS.CALLING || MainActivity.mCallController.mCallInfo.getRESI() == CALLSTATUS.TALKING) {
                            MainActivity.mCallController.ui_callEnd();
                            mySocket s = new mySocket(RemoteIDInfo.strIP, "BYE");
                            s.start();
                        }
                        else {
                            mySocket s = new mySocket(RemoteIDInfo.strIP, "BYE");
                            s.start();
                            Log.w(TAG, "[onKeyDown] CallStatus is not accept to cancel!!");
                            RemoteIDInfo.InitVariables();
                            super.setChangeScreen(ID.SCREENS.Main);
                        }
                    } else {
                        mySocket s = new mySocket(RemoteIDInfo.strIP, "BYE");
                        s.start();
                        RemoteIDInfo.InitVariables();
                        super.setChangeScreen(ID.SCREENS.Main);
                    }
                } else if (keyCode == Declare.Button.STAR) {
                    if (!MainActivity.mCallController.bTalkTestModeEnable) {
                        if (Global.TargetInputStep == TARGETINFOINPUTSTEP.DONG) {
                            Global.TargetInputStep = TARGETINFOINPUTSTEP.HO;
                        }
                    } else {
                        if (MainActivity.mCallController.mCallInfo.getRESI() != CALLSTATUS.TALKING)
                            return;
                        changeTalkVol(true);
                    }
                } else if (keyCode == Declare.Button.SHARP) {
                    if (MainActivity.mCallController.mCallInfo.getRESI() == CALLSTATUS.TALKING) {
                        if (MainActivity.mCallController.bTalkTestModeEnable) changeTalkVol(false);
                    } else {
                        if (Global.TargetInputStep == TARGETINFOINPUTSTEP.HO) {
                            if (ConfigValue.eHouseDivision == SetValue.TRUE) {
                                RemoteIDInfo.bRentRoomSelected = true;
                                RemoteIDInfo.nHo_Extension = 1;
                            }
                        }
                    }
                }
                updateScreen();
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] onBrReceive(...) : " + e);
            e.printStackTrace();
        }
        super.onBrReceive(intent);
    }

    @Override
    protected void onKeyDown(int keyCode, KeyEvent event) {
        try {
            super.onKeyDown(keyCode, event);
//            LOG_DEBUG("[onKeyDown] keyCode [" + keyCode + "], event [" + event + "]");
            if (bInputDelay) {
                Log.w(TAG, "[onKeyDown] bInputDelay [" + bInputDelay + "], Ignore Key Input");
                return;
            }

            if (Declare.Button.NUMBER_00 <= keyCode && keyCode <= Declare.Button.NUMBER_09) {
                if (Global.TargetInputStep == TARGETINFOINPUTSTEP.DONG) {
                    int nPressedNum = keyCode - 7;
                    RemoteIDInfo.strDong += nPressedNum;
                    if (RemoteIDInfo.strDong.length() > MAXLENGTH_DONG) {
                        RemoteIDInfo.strDong = RemoteIDInfo.strDong.substring(1, 5);
                    }
                } else if (Global.TargetInputStep == TARGETINFOINPUTSTEP.HO) {
                    int nPressedNum = keyCode - 7;
                    RemoteIDInfo.strHo += nPressedNum;
                    if (RemoteIDInfo.strHo.length() > MAXLENGTH_HO) {
                        RemoteIDInfo.strHo = RemoteIDInfo.strHo.substring(1, 5);
                    }
                }
            } else if (keyCode == Declare.Button.CALL) {
                LOG_INFO("[onKeyDown] Declare.Button.CALL");
                startInputDelayTimer();
                if (bFUNCBlock) return;
                if (Global.TargetInputStep == TARGETINFOINPUTSTEP.DONE) return;
                Global.TargetInputStep = TARGETINFOINPUTSTEP.DONE;

                if (MainActivity.mCallController.mCallInfo.getIDLECnt() != MainActivity.mCallController.mCallInfo.IDLECNT_MAX) {
                    MainActivity.mSound.PlayMent_lobby(R.raw.inputfail);
                    MainActivity.mCallController.mCallInfo.printCallStatus();
                    LOG("[onKeyDown] CallStatus is not idle!!");
                    super.setChangeScreen(ID.SCREENS.Main);
                    return;
                }

                if (MINLENGTH_DONG > RemoteIDInfo.strDong.length() || MINLENGTH_HO > RemoteIDInfo.strHo.length()) {
                    initCallVariables();
                    MainActivity.mSound.PlayMent_lobby(R.raw.retryinput);
                    updateScreen();
                    return;
                }

                LOG("[onKeyDown] strDong [" + RemoteIDInfo.strDong + "], strHo [" + RemoteIDInfo.strHo + "], strIP [" + RemoteIDInfo.strIP + "]");

                if (ConfigValue.eCallLevel == SetValue.Level_Line) {
                    if (!Global.isExistResi(Integer.parseInt(RemoteIDInfo.strHo))) {
                        LOG("[onKeyDown] " + RemoteIDInfo.strHo + " ho is not exist!!");
                        initCallVariables();
                        MainActivity.mSound.PlayMent_lobby(R.raw.confirmsetting);
                        super.setChangeScreen(ID.SCREENS.Main);
                        return;
                    }
                }

                try {
                    if (RemoteIDInfo.bRentRoomSelected)
                        RemoteIDInfo.strIP = EthernetCtrl.makeIPAddress(DeviceType.RENTRESIDENCE, RemoteIDInfo.strDong, RemoteIDInfo.strHo);
                    else
                        RemoteIDInfo.strIP = EthernetCtrl.makeIPAddress(DeviceType.RESIDENCE, RemoteIDInfo.strDong, RemoteIDInfo.strHo);
                } catch (Exception e) {
                    MainActivity.mSound.PlayMent_lobby(R.raw.retryinput);
                    Log.e(TAG, "[Exception] onKeyDown -> EthernetCtrl.makeIPAddress(...) : " + e);
                    e.printStackTrace();
                }

                if (!send_check_sip_activation_request(RemoteIDInfo.strIP)) {
                    initCallVariables();
                    MainActivity.mSound.PlayMent_lobby(R.raw.trylater);
                    super.setChangeScreen(ID.SCREENS.Main);
                }

                MainActivity.mCallController.mCallInfo.setCallStatus(CALLTYPE.RESIDENCE, CALLSTATUS.TRYING_CALL);
            } else if (keyCode == Declare.Button.CANCEL || keyCode == Declare.Button.TACT_CANCEL) {

                Global.stopMelodyRepeat();
                Global.stopMelodyRepeat();

                Global.changeVolumeMoIPMode(CALLTYPE.NONE);
                MainActivity.mCallController.mCallInfo.setCallStatus(CALLTYPE.RESIDENCE, CALLSTATUS.IDLE);
                MainActivity.mCallController.setCallTimer(MainActivity.mCallController.mCTT.KILLTIMER);

                if (MainActivity.mCallController.mCallInfo.getIDLECnt() != MainActivity.mCallController.mCallInfo.IDLECNT_MAX) {
                    if (MainActivity.mCallController.mCallInfo.getRESI() == CALLSTATUS.CALLING || MainActivity.mCallController.mCallInfo.getRESI() == CALLSTATUS.TALKING) {
                        MainActivity.mCallController.ui_callEnd();
                        mySocket s = new mySocket(RemoteIDInfo.strIP, "BYE");
                        s.start();
                    }
                    else {
                        mySocket s = new mySocket(RemoteIDInfo.strIP, "BYE");
                        s.start();
                        Log.w(TAG, "[onKeyDown] CallStatus is not accept to cancel!!");
                        RemoteIDInfo.InitVariables();
                        super.setChangeScreen(ID.SCREENS.Main);
                    }
                } else {
                    mySocket s = new mySocket(RemoteIDInfo.strIP, "BYE");
                    s.start();
                    RemoteIDInfo.InitVariables();
                    super.setChangeScreen(ID.SCREENS.Main);
                }
            } else if (keyCode == Declare.Button.STAR) {
                if (!MainActivity.mCallController.bTalkTestModeEnable) {
                    if (Global.TargetInputStep == TARGETINFOINPUTSTEP.DONG) {
                        Global.TargetInputStep = TARGETINFOINPUTSTEP.HO;
                    }
                } else {
                    if (MainActivity.mCallController.mCallInfo.getRESI() != CALLSTATUS.TALKING)
                        return;
                    changeTalkVol(true);
                }
            } else if (keyCode == Declare.Button.SHARP) {
                if (MainActivity.mCallController.mCallInfo.getRESI() == CALLSTATUS.TALKING) {
                    if (MainActivity.mCallController.bTalkTestModeEnable) changeTalkVol(false);
                } else {
                    if (Global.TargetInputStep == TARGETINFOINPUTSTEP.HO) {
                        if (ConfigValue.eHouseDivision == SetValue.TRUE) {
                            RemoteIDInfo.bRentRoomSelected = true;
                            RemoteIDInfo.nHo_Extension = 1;
                        }
                    }
                }
            }
            updateScreen();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] onKeyDown(...) : " + e);
            e.printStackTrace();
        }
    }

    private void updateScreen() {
        try {
            LOG("[updateScreen] MainActivity.mCallController.mCallInfo.getRESI() = " + MainActivity.mCallController.mCallInfo.getRESI());
            if (MainActivity.mCallController.mCallInfo.getRESI() == CALLSTATUS.IDLE) {
                if (RemoteIDInfo.strDong != "") {
                    // 첫자리에 "0"이 출력되지 않도록 숫자로 변경하면서 "0"을 제거하고, 다시 String으로 변환한다.
                    RemoteIDInfo.nDong = Integer.parseInt(RemoteIDInfo.strDong);
                    RemoteIDInfo.strDong = Integer.toString(RemoteIDInfo.nDong);
                }

                if (RemoteIDInfo.strHo != "") {
                    // 첫자리에 "0"이 출력되지 않도록 숫자로 변경하면서 "0"을 제거하고, 다시 String으로 변환한다.
                    RemoteIDInfo.nHo = Integer.parseInt(RemoteIDInfo.strHo);
                    RemoteIDInfo.strHo = Integer.toString(RemoteIDInfo.nHo);
                }
                strText_Instruction = TextResources.strInputResidenceInfo;
            } else if (MainActivity.mCallController.mCallInfo.getRESI() == CALLSTATUS.TRYING_CALL) {
                strText_Instruction = TextResources.strTryingResidence;
            } else if (MainActivity.mCallController.mCallInfo.getRESI() == CALLSTATUS.WAITNG_INVITE_ACK || MainActivity.mCallController.mCallInfo.getRESI() == CALLSTATUS.CALLING || MainActivity.mCallController.mCallInfo.getRESI() == CALLSTATUS.CALLED) {
//                setAnimation(true);
                strText_Instruction = TextResources.strCallingResidence;
            } else if (MainActivity.mCallController.mCallInfo.getRESI() == CALLSTATUS.TALKING) {
                strText_Instruction = TextResources.strTalkingResidence;
                displayTalkVolume();
            } else {
//                setAnimation(false);
                strText_Instruction = "";
            }

            Text_ResidenceInfo_Dong.setText(RemoteIDInfo.strDong);

            String strDisplayHo = "";
            if (RemoteIDInfo.bRentRoomSelected) strDisplayHo = RemoteIDInfo.strHo + "-" + RemoteIDInfo.nHo_Extension;
            else strDisplayHo = RemoteIDInfo.strHo;

            Log.w(TAG, "[updateScreen] strDisplayHo [" + strDisplayHo + "], strDisplayHo.length() [" + strDisplayHo.length() + "]");
            if (strDisplayHo.length() > MAXLENGTH_HO) {
                Log.w(TAG, "[updateScreen] ========== JEFF 1 ==========");
                Text_ResidenceInfo_Ho.setTextSize(0, (float) nFontSize_DONGHO_Rent[ConfigValue.DEVICE_MODELTYPE]);
            }
            else {
                Log.w(TAG, "[updateScreen] ========== JEFF 2 ==========");
                Text_ResidenceInfo_Ho.setTextSize(0, (float) nFontSize_DONGHO[ConfigValue.DEVICE_MODELTYPE]);
            }

            Text_ResidenceInfo_Ho.setText(strDisplayHo);
            Text_Instruction.setText(strText_Instruction);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] updateScreen()");
            e.printStackTrace();
        }
    }

    private void setAnimation(boolean bSet) {
        try {
            if (bSet) {
                Image_Residence.setVisibility(View.VISIBLE);
                Image_Call_Anim.startAnimation(mAnimation); // 애니메이션 시작
            } else {
                Image_Call_Anim.clearAnimation(); // 애니메이션 해제
                Image_Call_Anim.setVisibility(View.GONE);
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] setAnimation(boolean bSet)");
            e.printStackTrace();
        }
    }

    private void displayTalkVolume() {
        try {
            if (!MainActivity.mCallController.bTalkTestModeEnable) return;
            strText_Instruction = strText_Instruction + " [음량 " + nTalkVolume + "]";
        } catch (Exception e) {
            Log.e(TAG, "[Exception] displayTalkVolume() : " + e);
            e.printStackTrace();
        }
    }

    private POSITION getPosition(int nID) {
        POSITION position = new POSITION();
        position.SetPosition(0, 0, 480, 272);
        try {
            switch (nID) {
                case ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.BACKGROUND:
                    if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_700) position.SetPosition(0, 0, 800, 480);
                    else position.SetPosition(0, 0, 480, 272);
                    return position;

                case ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.RESIDENCEINFO_DONG:
                    if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_700) position.SetPosition(20, 111, 332, 152);
                    else position.SetPosition(38, 65, 168, 88);
                    return position;

                case ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.RESIDENCEINFO_HO:
                    if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_700) position.SetPosition(402, 111, 332, 152);
                    else position.SetPosition(238, 65, 168, 88);
                    return position;

//                case ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.RESIDENCEINFO_HO:
//                    if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_300) position.SetPosition(113, 47, 254, 108);
//                    else if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_700) position.SetPosition(0, 0, 0, 0);
//                    return position;

                case ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE_DONG:
                    if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_700) position.SetPosition(343, 228, 37, 38);
                    else position.SetPosition(204, 67, 36, 88);
                    return position;

                case ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE_HO:
                    if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_700) position.SetPosition(725, 228, 37, 38);
                    else position.SetPosition(406, 67, 36, 88);
                    return position;

//                case ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE_HO:
//                    if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_300) position.SetPosition(367, 78, 36, 88);
//                    else if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_700) position.SetPosition(0, 0, 0, 0);
//                    return position;

                case ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE:
                    if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_700) position.SetPosition(280, 91, 240, 240);
                    else position.SetPosition(152, 21, 180, 180);
                    return position;

                case ID.SCREENS.TALKRESIDENCE.ELEMENTS.IMAGES.RESIDENCE_ANIM:
                    if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_700) position.SetPosition(280, 91, 240, 240);
                    else position.SetPosition(150, 21, 180, 180);
                    return position;
                    
                case ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.INSTRUCTION:
                    if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_700) position.SetPosition(0, 381, 800, 99);
                    else position.SetPosition(0, 216, 480, 56);
                    return position;

                case ID.SCREENS.TALKRESIDENCE.ELEMENTS.TEXTS.CHATMESSAGE:
                    if (ConfigValue.DEVICE_MODELTYPE == Global.MODEL_ILP_700) position.SetPosition(80, 420, 600, 80);
                    else position.SetPosition(47, 170, 386, 90);
                    return position;

                default:
                    return position;
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] getPosition() : " + e);
            e.printStackTrace();
            return position;
        }
    }

    private void setCallLevel() {
        try {
            if (ConfigValue.eCallLevel == SetValue.Level_Line || ConfigValue.eCallLevel == SetValue.Level_Dong) {
                Global.TargetInputStep = TARGETINFOINPUTSTEP.HO;
                RemoteIDInfo.strDong = ConfigValue.strDevice_Dong;
                if (RemoteIDInfo.n1stNumforResicall > 0) {
                    RemoteIDInfo.strHo = Integer.toString(RemoteIDInfo.n1stNumforResicall);
                }
            } else if (ConfigValue.eCallLevel == SetValue.Level_Entire) {
                Global.TargetInputStep = TARGETINFOINPUTSTEP.DONG;
                if (RemoteIDInfo.n1stNumforResicall > 0) {
                    RemoteIDInfo.strDong = Integer.toString(RemoteIDInfo.n1stNumforResicall);
                }
            } else {
                Global.TargetInputStep = TARGETINFOINPUTSTEP.HO;
                if (RemoteIDInfo.n1stNumforResicall > 0) {
                    RemoteIDInfo.strHo = Integer.toString(RemoteIDInfo.n1stNumforResicall);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] setCallLevel()");
            e.printStackTrace();
        }
    }

    private void initCallVariables() {
        try {
            RemoteIDInfo.InitVariables();
            setCallLevel();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] initCallVariables()");
            e.printStackTrace();
        }
    }

    public class mySocket extends Thread {

        Socket s;
        String toCall;
        BufferedWriter output;
        BufferedReader input;
        String message;


        public mySocket (String toCall, String msg) {
            this.toCall = toCall;
            this.message = msg;

        }

        @Override
        public void run() {
            try {
                s = new Socket(toCall, 4001);
                s.setTcpNoDelay(true);
                output = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
                input = new BufferedReader(new InputStreamReader(s.getInputStream()));

                int what = -1;
                output.write(message);
                output.flush();
                while (true) {

                    String msg = input.readLine();
                    if (msg != null) {
                        LOG_INFO("[TCPServer11] " + msg);
                        if (msg.equals("ACK")) {
                            if(message.equals("BYE"))
                            {
                                Global.stopMelodyRepeat();

                                Global.changeVolumeMoIPMode(CALLTYPE.NONE);
                                MainActivity.mCallController.mCallInfo.setCallStatus(CALLTYPE.RESIDENCE, CALLSTATUS.IDLE);
                                MainActivity.mCallController.setCallTimer(MainActivity.mCallController.mCTT.KILLTIMER);
                            }
                            s.close();
                            break;
                        }


                    }
                }
                if (s != null)
                    s.close();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private boolean send_check_sip_activation_request(String strTargetIP) {
        try {

            bFUNCBlock = true;

            mySocket s = new mySocket(RemoteIDInfo.strIP, "HEY");
            s.start();


            return true;
//            Request_check_sip_activation check_sip_activation = new Request_check_sip_activation(mContext);
//            bFUNCBlock = true;
//            if (check_sip_activation.send_check_sip_activation_request(strTargetIP)) {
//                check_sip_activation.setResultCtrl(new iMAPResultCtrl() {
//
//                    @Override
//                    public void onResult(iMAPResult eResult) {
//                        LOG_INFO("[send_check_sip_activation_request] (onResult) eResult =" + eResult);
//                        ((MainActivity) mContext).checkMemoryUsage();
//                        if (eResult == iMAPResult.OK) {
//                            if (RemoteIDInfo.bRentRoomSelected) {
//                                MainActivity.mCallController.tryMoIPCall(CALLTYPE.RENTRESIDENCE, RemoteIDInfo.strDong, RemoteIDInfo.strHo);
//                            } else {
//                                MainActivity.mCallController.tryMoIPCall(CALLTYPE.RESIDENCE, RemoteIDInfo.strDong, RemoteIDInfo.strHo);
//                            }
//                            ((MainActivity) mContext).ctrlVideoSurface(true);
//                        } else {
//                            bFUNCBlock = false;
//                            initCallVariables();
//                            MainActivity.mSound.Play_lobby(R.raw.trylater);
//                            MainActivity.mCallController.mCallInfo.setCallStatus(CALLTYPE.RESIDENCE, CALLSTATUS.IDLE);
//                            ((MainActivity) mContext).setChangeScreen(ID.SCREENS.Main, false);
//                        }
//                    }
//                });
//                return true;
//            }
//            bFUNCBlock = false;
//            return false;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] send_check_sip_activation_request(strTargetIP)");
            e.printStackTrace();
            bFUNCBlock = false;
            return false;
        }
    }

    private boolean send_chat_message_request(String strTargetIP, String strMessage) {
        try {
            Request_chat_message chat_message = new Request_chat_message(mContext);
            if (chat_message.send_chat_message_request(strTargetIP, strMessage)) {
                chat_message.setResultCtrl(new iMAPResultCtrl() {

                    @Override
                    public void onResult(iMAPResult eResult) {
                        LOG_INFO("[send_chat_message_request] (onResult) eResult =" + eResult);
                    }
                });
                return true;
            }
            return false;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] send_chat_message_request(strTargetIP)");
            e.printStackTrace();
            return false;
        }
    }

    @Override
    public void onCallEvent(CALLSTATUS eCallStatus, CALLTYPE eCallType, String strRemoteIP, String strRemoteSIPID, String strMessage) {
        try {
            LOG_INFO("[onCallEvent] eCallStatus [" + eCallStatus + "], eCallType [" + eCallType + "], strRemoteIP [" + strRemoteIP + "], strRemoteSIPID [" + strRemoteSIPID + "], strMessage [" + strMessage + "]");

            if (eCallType == CALLTYPE.RESIDENCE || eCallType == CALLTYPE.NONE) {
                MainActivity.mCallController.setRemoteInfo(strRemoteSIPID, strRemoteIP);
                if (eCallStatus == CALLSTATUS.CALLING) {
                    bRcvCancel = false;
                    Global.playMelodyRepeat(ConfigValue.eCallMelody_Resi);
                    ((MainActivity) mContext).cancelAutoScreenChange();
                    MainActivity.mCallController.setCallTimer(MainActivity.mCallController.mCTT.CALLING);
                    updateScreen();
                } else if (eCallStatus == CALLSTATUS.CALLED) {
                    bRcvCancel = false;
                    Global.playMelodyRepeat(ConfigValue.eCallMelody_Resi);
                    ((MainActivity) mContext).cancelAutoScreenChange();
                    MainActivity.mCallController.setCallTimer(MainActivity.mCallController.mCTT.CALLED);
                    updateScreen();
                    MainActivity.m_bCallType = 2;
                    MainActivity.mIOInterface.setAnalogCameraPower(true);

                    //MainActivity.mCallController.mVideoJNI.mV40IFCCD.videoSet(true);


                    //MainActivity.mCallController.mVideoJNI.setCameraSurface(null, 640, 480, 0, 0);
                    //MainActivity.mCallController.mVideoJNI.encoderStartOperation();
                    ((MainActivity) mContext).ctrlVideoSurface(true);
                } else if (eCallStatus == CALLSTATUS.TALKING) {
                    MainActivity.mCallController.mCallInfo.setRemoteCallOwner(REMOTECALLOWNER.RESIDENCE);
                    Global.stopMelodyRepeat();
                    MainActivity.mCallController.setCallTimer(MainActivity.mCallController.mCTT.RESIDENCEnLOBBY);
                    updateScreen();
                    Thread.sleep(500);
                    Global.changeVolumeMoIPMode(CALLTYPE.RESIDENCE); // handler로 코드 수정 (통화패스 확인 후 볼륨 셋팅)
                    mPathCheckHandler.sendEmptyMessage(0);
                } else if (eCallStatus == CALLSTATUS.END) {
                    Global.stopMelodyRepeat();
//                    stopVideo();
                    Global.changeVolumeMoIPMode(CALLTYPE.NONE);
                    MainActivity.mCallController.mCallInfo.setCallStatus(CALLTYPE.RESIDENCE, CALLSTATUS.IDLE);
                    MainActivity.mCallController.setCallTimer(MainActivity.mCallController.mCTT.KILLTIMER);
                    super.setChangeScreen(ID.SCREENS.Main);
                } else if (eCallStatus == CALLSTATUS.REJECT) {
                    if (bRcvCancel) return;
                    Global.stopMelodyRepeat();
//                    stopVideo();
                    Global.changeVolumeMoIPMode(CALLTYPE.NONE);
                    MainActivity.mSound.PlayMent_lobby(R.raw.trylater);
                    MainActivity.mCallController.mCallInfo.setCallStatus(CALLTYPE.RESIDENCE, CALLSTATUS.IDLE);
                    MainActivity.mCallController.setCallTimer(MainActivity.mCallController.mCTT.KILLTIMER);
                    super.setChangeScreen(ID.SCREENS.Main);
                } else if (eCallStatus == CALLSTATUS.BUSY) {
                    Global.stopMelodyRepeat();
//                    stopVideo();
                    Global.changeVolumeMoIPMode(CALLTYPE.NONE);
                    MainActivity.mSound.PlayMent_lobby(R.raw.busytrylater);
                    MainActivity.mCallController.mCallInfo.setCallStatus(CALLTYPE.RESIDENCE, CALLSTATUS.IDLE);
                    MainActivity.mCallController.setCallTimer(MainActivity.mCallController.mCTT.KILLTIMER);
                    super.setChangeScreen(ID.SCREENS.Main);
                } else if (eCallStatus == CALLSTATUS.CANCEL) {
                    bRcvCancel = true;
                    Global.stopMelodyRepeat();
//                    stopVideo();
                    Global.changeVolumeMoIPMode(CALLTYPE.NONE);
                    MainActivity.mCallController.mCallInfo.setCallStatus(CALLTYPE.RESIDENCE, CALLSTATUS.IDLE);
                    MainActivity.mCallController.setCallTimer(MainActivity.mCallController.mCTT.KILLTIMER);
                    super.setChangeScreen(ID.SCREENS.Main);
                } else if (eCallStatus == CALLSTATUS.FORWARD) {
                    bRcvCancel = true;
                    Global.stopMelodyRepeat();
//                    stopVideo();
                    Global.changeVolumeMoIPMode(CALLTYPE.NONE);
                    MainActivity.mCallController.mCallInfo.setCallStatus(CALLTYPE.RESIDENCE, CALLSTATUS.IDLE);
                    MainActivity.mCallController.setCallTimer(MainActivity.mCallController.mCTT.KILLTIMER);
                    if (!tryAutoCall(strMessage)) super.setChangeScreen(ID.SCREENS.Main);
                } else {
                    Log.w(TAG, "[onCallEvent] Incorrect eCallStatus!!! eCallStatus = " + eCallStatus);
                }
            } else {
                Log.w(TAG, "[onCallEvent] Incorrect eCallType!!! eCallType = " + eCallType);
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] onSIPEvent(...) : " + e);
            e.printStackTrace();
        }
    }

    @Override
    public void onVideoSet(boolean bSet) {
        try {
            LOG_INFO("[onVideoSet] bSet [" + bSet + "]");
        } catch (Exception e) {
            Log.e(TAG, "[Exception] onVideoSet(...) : " + e);
            e.printStackTrace();
        }
    }

    @Override
    public void onChatEvent(CHATEVENT eEventType, CALLTYPE eCallType, String strRemoteIP, String strRemoteSIPID, String strMessage) {
        try {
            LOG("[onChatEvent] eEventType [" + eEventType + "], eCallType [" + eCallType + "], strRemoteIP [" + strRemoteIP + "], strRemoteSIPID [" + strRemoteSIPID + "], strMessage [" + strMessage + "]");

            if (eEventType == CHATEVENT.TRY) {
                ((MainActivity) mContext).sendHandlerMsg(HANDLERMSG.START_CHATMODE, 0, 0);
                ((MainActivity) mContext).setTTSEventListener(this);
                strChatTargetIP = strRemoteIP;
            } else {
                // 기타
                LOG_WARN("[CallScenarioManager] not acceptable eEventType!! [" + eEventType + "]");
            }

        } catch (Exception e) {
            Log.e(TAG, "[Exception] onChatEvent(CHATEVENT eEventType, CALLTYPE eCallType, String strRemoteIP, String strRemoteSIPID, String strMessage)");
            e.printStackTrace();
        }
    }

    @Override
    public void onChatMessage(String strMessage) {
        try {
            LOG_INFO("[onChatMessage] strMessage [" + strMessage + "]");
            if (MainActivity.mCallController.mCallInfo.getRESI() == CALLSTATUS.TALKING) {
                strText_ChatMessage = strMessage;
                if (((MainActivity) mContext).isSTTRun()) {
                    ((MainActivity) mContext).cancelSTT();
                }
                ((MainActivity) mContext).playTTS(strMessage);
                sendHandlerMsg(TALKRESIDENCE_HD_MSG.DISPLAY_CHATMESSAGE, 0, 0, strMessage);
            } else {
                Log.w(TAG, "[onChatMessage] CallStatus is not talking!! [" + MainActivity.mCallController.mCallInfo.getGUARD() + "]");
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] onChatMessage(String strMessage) : " + e);
            e.printStackTrace();
        }
    }

    @Override
    public void onTTSEvent(TTSEVENT eTTSEvent, String strMessage) {
        try {
            LOG("[onTTSEvent] eTTSEvent [" + eTTSEvent + "], strMessage [" + strMessage + "]");
            if (eTTSEvent == TTSEVENT.TTS_SPEECH_END) {
                startSTT();
            } else if (eTTSEvent == TTSEVENT.TTS_ERROR) {

            } else if (eTTSEvent == TTSEVENT.STT_READY) {
                strText_ChatMessage = "말씀하세요.";
                sendHandlerMsg(TALKRESIDENCE_HD_MSG.DISPLAY_CHATMESSAGE, 0, 0, strText_ChatMessage);
            } else if (eTTSEvent == TTSEVENT.STT_SUCCESS) {
                strText_ChatMessage = strMessage;
                send_chat_message_request(strChatTargetIP, strText_ChatMessage);
                sendHandlerMsg(TALKRESIDENCE_HD_MSG.DISPLAY_CHATMESSAGE, 0, 0, strText_ChatMessage);
            } else if (eTTSEvent == TTSEVENT.STT_ERROR) {

            } else {
                LOG_INFO("[onTTSEvent] eTTSEvent is not acceptable!! [" + eTTSEvent + "]");
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] onChatMessage(String strMessage) : " + e);
            e.printStackTrace();
        }
    }

    private void startSTT() {
        try {
            ((MainActivity) mContext).startSTT();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] startSTT()");
            e.printStackTrace();
        }
    }

    private void displayChatMessage(String strMessage) {
        try {
            Text_ChatMessage.setText(strMessage);
            Text_ChatMessage.setFocusable(true);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] displayChatMessage(String strMessage) : " + e);
            e.printStackTrace();
        }
    }

//    private void stopVideo() {
//        try {
//            LOG_INFO("[stopVideo] ===== START =====");
//            ((MainActivity) mContext).ctrlVideoSurface(false);
//        } catch (Exception e) {
//            Log.e(TAG, "[Exception] stopVideo() : " + e);
//            e.printStackTrace();
//        }
//    }

    int nTalkVolume = Global.getMoIPoVolume();
    private void changeTalkVol(boolean bUp) {
        try {
            LOG("[changeTalkVol] bUp = " + bUp);
            if (bUp) {
                nTalkVolume++;
                if (nTalkVolume > 10) nTalkVolume = 10;
            } else {
                nTalkVolume--;
                if (nTalkVolume < 1) nTalkVolume = 1;
            }
            LOG("[changeTalkVol] nTalkVolume = " + nTalkVolume);
            Global.setMoIPVolume(Global.nMoIPVolumeTable_Residence[nTalkVolume]);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] changeTalkVol(bUp) : " + e);
            e.printStackTrace();
        }
    }

    private void sendHandlerMsg(int what, int arg1, int arg2, String strMessage) {
        try {
            LOG("[sendHandlerMsg] what [" + what + "], arg1 [" + arg1 + "], arg2 [" + arg2 + "], strMessage [" + strMessage + "]");
            Message HandleMsg = TalkResidenceHandler.obtainMessage();
            HandleMsg.what = what;
            HandleMsg.arg1 = arg1;
            HandleMsg.arg2 = arg2;
            HandleMsg.obj = strMessage;
            TalkResidenceHandler.sendMessage(HandleMsg);
        } catch (Exception e) {
            Log.e(TAG, "[Exception] sendHandlerMsg(int what, int arg1, int arg2, String strMessage)");
            e.printStackTrace();
        }
    }

    private boolean tryAutoCall(String strAutoCallInfo) {
        try {
            if (bAutoCallRun) return false;
            bAutoCallRun = true;
            LOG("[tryAutoCall] strAutoCallInfo [" + strAutoCallInfo + "]");
            String[] strParse_01 = strAutoCallInfo.split(":");
            String[] strParse_02 = strParse_01[1].split("@");
            String[] strParse_03 = strParse_02[1].split(":");
            String strForwardTarget_SIPID = strParse_02[0];
            String strForwardTarget_IP = strParse_03[0];

            CALLTYPE eCallType = MainActivity.mCallController.tryAutoMoIPCall(strForwardTarget_IP, strForwardTarget_SIPID);
            LOG("[tryAutoCall] eCallType [" + eCallType + "]");
            if (eCallType == CALLTYPE.FRONT || eCallType == CALLTYPE.LOBBY || eCallType == CALLTYPE.PSTN || eCallType == CALLTYPE.NONE)
                return false;
            else if (eCallType == CALLTYPE.GUARD) {
                ((MainActivity) mContext).setChangeScreen(ID.SCREENS.Talk_Guard, false);
                return true;
            } else if (eCallType == CALLTYPE.RESIDENCE) {
                ((MainActivity) mContext).setChangeScreen(ID.SCREENS.Talk_Residence, false);
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] tryAutoCall(String strAutoCallInfo) : " + e);
            e.printStackTrace();
            return false;
        }
    }

    private void doAutoCall() {
        try {
            if (RemoteIDInfo.bAutoCall) {
                LOG("[doAutoCall] strDong [" + RemoteIDInfo.strDong + "], strHo [" + RemoteIDInfo.strHo + "], strIP [" + RemoteIDInfo.strIP + "]");
                if (!send_check_sip_activation_request(RemoteIDInfo.strIP)) {
                    initCallVariables();
                    MainActivity.mSound.PlayMent_lobby(R.raw.trylater);
                    updateScreen();
                    return;
                }
                MainActivity.mCallController.mCallInfo.setCallStatus(CALLTYPE.GUARD, CALLSTATUS.TRYING_CALL);
                updateScreen();
            } else {
                LOG("[doAutoCall] AutoCall is not activated!!");
            }
        } catch (Exception e) {
            Log.e(TAG, "[Exception] doAutoCall() : " + e);
            e.printStackTrace();
        }
    }

    class TextResources {
        static final String strInputResidenceInfo = "세대 호수를 입력하세요.";
//        static final String strInputResidenceInfo = "세대 호출 : 호수 + 호출";
        static final String strTryingResidence = "세대를 호출합니다.";
        static final String strCallingResidence = "세대를 호출중입니다.";
        static final String strTalkingResidence = "세대와 통화중입니다.";
    }

    private class TALKRESIDENCE_HD_MSG {
        private static final int DISPLAY_CHATMESSAGE = 100;
        private static final int START_STT = 200;
        private static final int PLAYSOUND_STT_START = 300;
        private static final int PLAYSOUND_STT_END = 400;
    }

    private Handler mPathCheckHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
//            Log.d(TAG, "[mPathCheckHandler.handleMessage]");
            if (msg.what == 0) {
                if (MainActivity.mCallController.getTalkPath() == CALLPATH.MOIP_RESIDENCE)
                    mPathCheckHandler.sendEmptyMessageDelayed(1, 10);
                else mPathCheckHandler.sendEmptyMessageDelayed(0, 10);
            } else if (msg.what == 1) {
                Log.d(TAG, "[mPathCheckHandler.handleMessage] Handler finish!! CALLPATH [MOIP_RESIDENCE] setMoIPVolume");
                Global.changeVolumeMoIPMode(CALLTYPE.RESIDENCE);
                mVolumeCheckHandler.sendEmptyMessage(0);
            }
        }
    };

    private Handler mVolumeCheckHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                if (Global.getCurrentResiVolume(MainActivity.mIOInterface.getVolumeCtl()) != ConfigValue.nVolumeLevel_Talk) {
                    Global.changeVolumeMoIPMode(CALLTYPE.RESIDENCE);
                    mVolumeCheckHandler.sendEmptyMessageDelayed(0, 500);
                } else {
                    mVolumeCheckHandler.sendEmptyMessageDelayed(1, 500);
                }
            } else if (msg.what == 1) {
                Log.d(TAG, "[mVolumeCheckHandler.handleMessage] Handler finish!!");
            }
        }
    };

    private void startInputDelayTimer() {
        try {
            LOG("[startInputDelayTimer] ========== START ==========");
            bInputDelay = true;
            if (InputDelayTimer != null) {
                InputDelayTimer.cancel();
                InputDelayTimer = null;
            }

            InputDelayTimer = new CountDownTimer(3000, 1000) {
                @Override
                public void onTick(long millisUntilFinished) {
                    LOG("[startInputDelayTimer] onTick!!");
                }

                @Override
                public void onFinish() {
                    LOG("[startInputDelayTimer] onFinish!!");
                    bInputDelay = false;
                    quitInputDelayTimer();
                }
            };
            InputDelayTimer.start();
        } catch (Exception e) {
            Log.e(TAG, "[Exception] startInputDelayTimer()");
            e.printStackTrace();
        }
    }

    private void quitInputDelayTimer() {
        try {
            LOG("[quitInputDelayTimer] ========== START ==========");
            if (InputDelayTimer != null) {
                InputDelayTimer.cancel();
            }
            InputDelayTimer = null;
        } catch (Exception e) {
            Log.e(TAG, "[Exception] quitInputDelayTimer()");
            e.printStackTrace();
        }
    }

}   