package com.eugenefn.openapi.sample.view.screen;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.widget.NestedScrollView;

import com.eugenefn.openapi.intrf.IRealDataListener;
import com.eugenefn.openapi.intrf.ITranDataListener;
import com.eugenefn.openapi.proc.SmartChampAPI;
import com.eugenefn.openapi.proc.SmartChampReal;
import com.eugenefn.openapi.proc.SmartChampTran;
import com.eugenefn.openapi.sample.view.control.FIDSelectButton;
import com.eugenefn.openapi.sample.view.data.CondItemInfo;
import com.eugenefn.openapi.sample.view.data.CondSearchInfo;
import com.eugenefn.openapi.sample.view.data.CondSignalInfo;
import com.eugenefn.openapi.sample.view.util.ColorUtil;
import com.eugenefn.openapi.sample.view.util.LayoutUtil;
import com.eugenefn.openapi.sample.view.util.SampleUtil;
import com.eugenefn.openapi.sample.view.view.CondInfoListView;
import com.eugenefn.openapi.sample.view.view.CondItemListView;
import com.eugenefn.openapi.sample.view.view.CondSignalListView;

import java.util.ArrayList;

public class CondSearchView extends SiseBaseView
        implements ITranDataListener, IRealDataListener, View.OnClickListener, CondInfoListView.OnCondInfoListListener, CondItemListView.OnCondItemListListener, FIDSelectButton.OnFIDSelectionChangedListener {
    private static final String LOG_TAG = " 조건검색";

    private static final int CTRL_ID_QRY_CONDLIST = 100;
    private static final int CTRL_ID_QRY_ITEMLIST = 101;
    private static final int CTRL_ID_RESET_REALLIST = 102;

    // 화면 표시 뷰
    private CondInfoListView m_viewCondList;
    private CondSearchInfo m_infoSelectedCond;

    private TextView m_viewCondName;
    private FIDSelectButton m_buttonSelectFID;
    private CondItemListView m_viewItemList;

    private TextView m_viewRealName;
    private String m_strPacketCode; // 실시간 등록코드

    private CondSignalListView m_viewSignalList;

    // 데이터 처리
    private SmartChampTran m_tranCondList = null;				// 조건 조회
    private SmartChampTran m_tranItemList = null;       // 조건별 종목 조회
    private SmartChampTran m_tranRegReal = null; // 조건검색 실시간 등록

    private SmartChampReal m_realJ05 = null;    // 조건검색 실시간

    public CondSearchView(Context context)
    {
        super(context);

        setBackgroundColor(Color.WHITE);

        // TR 초기화
        m_tranCondList = new SmartChampTran(context);
        m_tranCondList.initInstance(this);
        m_tranCondList.setQueryFile("msvf007");
        m_tranCondList.setTranId("조건리스트조회");

        m_tranItemList = new SmartChampTran(context);
        m_tranItemList.initInstance(this);
        m_tranItemList.setQueryFile("msvf027");
        m_tranItemList.setTranId("조건종목시세조회");

        m_tranRegReal = new SmartChampTran(context);
        m_tranRegReal.initInstance(this);
        m_tranRegReal.setQueryFile("msvf028");
        m_tranRegReal.setTranId("조건종목실시간등록");

        // Real 초기화
        m_realJ05 = new SmartChampReal(context);
        m_realJ05.initInstance(this);
        m_realJ05.setQueryFile("J05");
        m_realJ05.setRealId("조검검색실시간감시");
    }

    //화면 초기화
    @Override
    public void initView(Context context, Activity activity)
    {
        super.initView(context, activity);

        NestedScrollView viewScroll = new NestedScrollView(context);

        LinearLayout layoutFrame = new LinearLayout(context);
        layoutFrame.setOrientation(LinearLayout.VERTICAL);

        layoutFrame.addView(makeCondListView(context), new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

        LayoutUtil.addSepLine(context, layoutFrame, ColorUtil.LIST_SEP_LINE, 1);

        layoutFrame.addView(makeItemListView(context), new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

        LayoutUtil.addSepLine(context, layoutFrame, ColorUtil.LIST_SEP_LINE, 1);

        layoutFrame.addView(makeRealListView(context), new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

        viewScroll.addView(layoutFrame, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));

        addView(viewScroll, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

        requestCondList();
    }

    public void releaseView()
    {
        removeAllViews();

        if(m_tranCondList != null) m_tranCondList.clearInstance();
        if(m_tranItemList != null) m_tranItemList.clearInstance();
        if(m_tranRegReal != null) m_tranRegReal.clearInstance();

        if(m_realJ05 != null) m_realJ05.clearInstance();
    }

    private LinearLayout makeCondListView(Context context)
    {
        LinearLayout layoutFrame = new LinearLayout(context);
        layoutFrame.setOrientation(LinearLayout.VERTICAL);

        LinearLayout layoutTitle = new LinearLayout(context);
        layoutTitle.setOrientation(LinearLayout.HORIZONTAL);

        TextView viewTitle = LayoutUtil.makeTextView(context, "조건 리스트");
        viewTitle.setPadding(PADDING_H, PADDING_V, PADDING_H, PADDING_V);

        Button buttonRefresh = LayoutUtil.makeCtrlButton(context, CTRL_ID_QRY_CONDLIST, "재조회");
        buttonRefresh.setOnClickListener(this);

        layoutTitle.addView(viewTitle, new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1));
        layoutTitle.addView(buttonRefresh, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

        layoutFrame.addView(layoutTitle, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int)SampleUtil.dipToPixels(context, 45)));

        m_viewCondList = new CondInfoListView(context, this);
        ViewGroup viewHead = m_viewCondList.makeHeadView(context);

        LayoutUtil.addSepLine(context, layoutFrame, ColorUtil.LIST_SEP_LINE, 1);
        layoutFrame.addView(viewHead, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        LayoutUtil.addSepLine(context, layoutFrame, ColorUtil.LIST_SEP_LINE, 1);
        layoutFrame.addView(m_viewCondList, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int)SampleUtil.dipToPixels(context, 150)));

        return layoutFrame;
    }

    private LinearLayout makeItemListView(Context context)
    {
        LinearLayout layoutFrame = new LinearLayout(context);
        layoutFrame.setOrientation(LinearLayout.VERTICAL);

        LinearLayout layoutTitle = new LinearLayout(context);
        layoutTitle.setOrientation(LinearLayout.HORIZONTAL);

        m_viewCondName = LayoutUtil.makeTextView(context, "조건별 종목 리스트");
        m_viewCondName.setPadding(PADDING_H, PADDING_V, PADDING_H, PADDING_V);
        m_viewCondName.setEllipsize(TextUtils.TruncateAt.MARQUEE);

        m_buttonSelectFID = new FIDSelectButton(context, this);
        m_buttonSelectFID.setDefaultList();

        Button buttonRefresh = LayoutUtil.makeCtrlButton(context, CTRL_ID_QRY_ITEMLIST, "재조회");
        buttonRefresh.setOnClickListener(this);

        layoutTitle.addView(m_viewCondName, new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1));
        layoutTitle.addView(m_buttonSelectFID, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
        layoutTitle.addView(buttonRefresh, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

        layoutFrame.addView(layoutTitle, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int)SampleUtil.dipToPixels(context, 45)));

        m_viewItemList = new CondItemListView(context, this);
        ViewGroup viewHead = m_viewItemList.makeHeadView(context);

        LayoutUtil.addSepLine(context, layoutFrame, ColorUtil.LIST_SEP_LINE, 1);
        layoutFrame.addView(viewHead, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        LayoutUtil.addSepLine(context, layoutFrame, ColorUtil.LIST_SEP_LINE, 1);

        layoutFrame.addView(m_viewItemList, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int)SampleUtil.dipToPixels(context, 200)));

        return layoutFrame;
    }

    private LinearLayout makeRealListView(Context context)
    {
        LinearLayout layoutFrame = new LinearLayout(context);
        layoutFrame.setOrientation(LinearLayout.VERTICAL);

        LinearLayout layoutTitle = new LinearLayout(context);
        layoutTitle.setOrientation(LinearLayout.HORIZONTAL);

        m_viewRealName = LayoutUtil.makeTextView(context, "실시간 감시 중지됨");
        m_viewRealName.setPadding(PADDING_H, PADDING_V, PADDING_H, PADDING_V);

        Button buttonRefresh = LayoutUtil.makeCtrlButton(context, CTRL_ID_RESET_REALLIST, "삭제");
        buttonRefresh.setOnClickListener(this);

        layoutTitle.addView(m_viewRealName, new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1));
        layoutTitle.addView(buttonRefresh, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

        layoutFrame.addView(layoutTitle, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int)SampleUtil.dipToPixels(context, 45)));

        m_viewSignalList = new CondSignalListView(context);
        ViewGroup viewHead = m_viewSignalList.makeHeadView(context);

        LayoutUtil.addSepLine(context, layoutFrame, ColorUtil.LIST_SEP_LINE, 1);
        layoutFrame.addView(viewHead, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        LayoutUtil.addSepLine(context, layoutFrame, ColorUtil.LIST_SEP_LINE, 1);

        layoutFrame.addView(m_viewSignalList, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, (int)SampleUtil.dipToPixels(context, 150)));

        return layoutFrame;
    }

    public void onRefreshView()
    {
        requestCondList();
    }

    private void requestCondList()
    {
        releaseRealReg();

        selectCondSearchInfo(null);

        if(m_viewItemList != null)
            m_viewItemList.clearList();

        if(m_viewCondList != null)
            m_viewCondList.clearList();

		if(m_tranCondList == null) return;

		m_tranCondList.clearInputData();
        m_tranCondList.clearOutputData();

        String strUserId = SmartChampAPI.getInstance().getLoginUserID();

        m_tranCondList.setDataValue( "InBlock1", "sUserID", 0, strUserId);

        m_tranCondList.requestData();
    }

    private void requestItemList()
    {
        releaseRealReg();

        if(m_viewItemList != null)
            m_viewItemList.clearList();

        if(m_infoSelectedCond == null) return;

        if(m_tranItemList == null) return;

        m_tranItemList.clearInputData();
        m_tranItemList.clearOutputData();

        String strUserId = SmartChampAPI.getInstance().getLoginUserID();
        String strFIDCount = m_buttonSelectFID.getFIDCount();
        String strFIDList = m_buttonSelectFID.getFIDList();

        m_tranItemList.setDataValue("InBlock1", "sUserID", 0, strUserId);
        m_tranItemList.setDataValue("InBlock1", "sDate", 0, m_infoSelectedCond.m_strSavedDate);
        m_tranItemList.setDataValue("InBlock1", "sTime", 0, m_infoSelectedCond.m_strSavedTime);
        m_tranItemList.setDataValue("InBlock1", "lSeq", 0, m_infoSelectedCond.m_strSeqNo);
        m_tranItemList.setDataValue("InBlock1", "lFieldEditCnt", 0, strFIDCount);
        m_tranItemList.setDataValue("InBlock1", "sFiledList", 0, strFIDList);

        m_tranItemList.requestData();
    }

    private void requestRealReg()
    {
        if(m_realJ05 != null)
            m_realJ05.releaseReal();

        if(m_tranRegReal == null) return;
        if(m_infoSelectedCond == null) return;

        m_tranRegReal.clearInputData();
        m_tranRegReal.clearOutputData();

        String strUserId = SmartChampAPI.getInstance().getLoginUserID();

        m_tranRegReal.setDataValue("InBlock1", "sUserID", 0, strUserId);
        m_tranRegReal.setDataValue("InBlock1", "sDate", 0, m_infoSelectedCond.m_strSavedDate);
        m_tranRegReal.setDataValue("InBlock1", "sTime", 0, m_infoSelectedCond.m_strSavedTime);
        m_tranRegReal.setDataValue("InBlock1", "lSeq", 0, m_infoSelectedCond.m_strSeqNo);
        m_tranRegReal.setDataValue("InBlock1", "sGubun", 0, "E");

        m_tranRegReal.requestData();
    }

    private void releaseRealReg()
    {
        if(m_realJ05 != null)
            m_realJ05.releaseReal();

        if(m_tranRegReal == null) return;
        if(m_infoSelectedCond == null) return;
        if(TextUtils.isEmpty(m_strPacketCode)) return;

        m_tranRegReal.clearInputData();
        m_tranRegReal.clearOutputData();

        String strUserId = SmartChampAPI.getInstance().getLoginUserID();

        m_tranRegReal.setDataValue("InBlock1", "sUserID", 0, strUserId);
        m_tranRegReal.setDataValue("InBlock1", "sDate", 0, m_infoSelectedCond.m_strSavedDate);
        m_tranRegReal.setDataValue("InBlock1", "sTime", 0, m_infoSelectedCond.m_strSavedTime);
        m_tranRegReal.setDataValue("InBlock1", "lSeq", 0, m_infoSelectedCond.m_strSeqNo);
        // 해제
        m_tranRegReal.setDataValue("InBlock1", "sGubun", 0, "D");
        m_tranRegReal.setDataValue("InBlock1", "sDelSeq", 0, m_strPacketCode);

        m_tranRegReal.requestData();

        m_strPacketCode = "";
    }

    private void requestCondReal(String strPacketCode)
    {
        if(m_realJ05 == null) return;

        m_realJ05.releaseReal();

        m_strPacketCode = strPacketCode;

        String strRegCode = strPacketCode.length() > 4 ? strPacketCode.substring(strPacketCode.length() - 4) : strPacketCode;
        m_realJ05.setDataValue("InBlock1", "sPacketCode", 0, strRegCode);

        m_realJ05.requestReal();
    }

    public void selectCondSearchInfo(CondSearchInfo info)
    {
        if(info == null)
        {
            m_viewCondName.setText("조건별 종목 리스트");
        } else {
            m_viewCondName.setText(info.m_strCondName);
        }

        m_infoSelectedCond = info;

        View view = findViewById(CTRL_ID_QRY_ITEMLIST);
        if(view != null) view.setEnabled(info != null);
    }
    @Override
    public void onTranBeforeRequest(String sTranID, boolean isNextQuery) {

    }

    @Override
    public void onTranDataReceived(String sTranID, String sMsgCode, String sMsgText)
    {
        SampleUtil.writeLog(LOG_TAG, String.format("onTranDataReceived [%s][%s][%s]", sTranID, sMsgCode, sMsgText));

        String strBlockName = "OutBlock1";

        if(sTranID.equals("조건리스트조회"))
        {
            strBlockName = "OutBlock2";

            int nDataCount = m_tranCondList.getDataCount(strBlockName);
            for(int i = 0; i < nDataCount; i++)
            {
                CondSearchInfo info = new CondSearchInfo();

                info.m_strSavedDate = m_tranCondList.getDataValue(strBlockName, "sDate", i);
                info.m_strSavedTime = m_tranCondList.getDataValue(strBlockName, "sTime", i);
                info.m_strSeqNo = m_tranCondList.getDataValue(strBlockName, "lSeq", i);
                info.m_strCondName = m_tranCondList.getDataValue(strBlockName, "sContName", i);
                info.m_strGroupName = m_tranCondList.getDataValue(strBlockName, "sGroupName", i);
                info.m_strCondDesc = m_tranCondList.getDataValue(strBlockName, "sMemo", i);

                m_viewCondList.addList(info);
            }
        } else if(sTranID.equals("조건종목시세조회"))
        {
            int nFieldCount = SampleUtil.getIntValue(m_tranItemList.getDataValue(strBlockName, "lOutFiledCnt", 0));
            int nFieldLength = SampleUtil.getIntValue(m_tranItemList.getDataValue(strBlockName, "sOutListpacketSize", 0));
            int nResultSize = nFieldCount * 16;

            strBlockName = "OutBlock2";
            int nDataCount = m_tranItemList.getDataCount(strBlockName);
            for(int i = 0; i < nDataCount; i++)
            {
                CondItemInfo info = new CondItemInfo();

                info.m_strItemCode = m_tranItemList.getDataValue(strBlockName, "sCode", i);
                info.m_strName = m_tranItemList.getDataValue(strBlockName, "sHname", i);
                info.m_strBasePrice = m_tranItemList.getDataValue(strBlockName, "sPrePrice", i);
                info.m_strOpenPrice = m_tranItemList.getDataValue(strBlockName, "sOpen", i);
                info.m_strHighPrice = m_tranItemList.getDataValue(strBlockName, "sHigh", i);
                info.m_strLowPrice = m_tranItemList.getDataValue(strBlockName, "sLow", i);
                info.m_strResult = m_tranItemList.getDataValue(strBlockName, "sResultFiled", i).substring(0, nResultSize);

                m_viewItemList.addList(info);
            }

            requestRealReg();
        } else if(sTranID.equals("조건종목실시간등록"))
        {
            String strGubun = m_tranRegReal.getDataValue(strBlockName, "sGubun", 0);

            if("D".equals(strGubun))
            {
                if(m_realJ05 != null) m_realJ05.releaseReal();
                m_strPacketCode = "";
                m_viewRealName.setText("실시간 감시 중0지됨");
            } else {
                String strPacketCode = m_tranRegReal.getDataValue(strBlockName, "sRegSeq", 0);

                requestCondReal(strPacketCode);

                m_viewRealName.setText("실시간 감시 시작됨");
            }
        }
    }

    @Override
    public void onTranError(String sTranID, String sErrCode, String sErrText) {
        Log.d(LOG_TAG, String.format("onTranError [%s] [%s][%s]", sTranID, sErrCode, sErrText));

        //if(sTranID.equals("주식매수주문"))
        {
            Toast.makeText(getContext(), sErrText, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onTranTimeout(String sTranID)
    {
        Log.e(LOG_TAG, String.format("TranId:%s ", sTranID));
    }

    @Override
    public void onRealBeforeRequest(String sRealId)
    {
    }

    @Override
    public void onRealDataReceived(String strRealId)
    {
        String strBlockName = "OutBlock1";

        if(strRealId.equals("조검검색실시간감시"))
        {
            String strDataSection = m_realJ05.getDataValue(strBlockName, "sDataSection", 0);
            String strPacketCode = m_realJ05.getDataValue(strBlockName, "sPacketCode", 0);
            String strDate = m_realJ05.getDataValue(strBlockName, "sSignaldate", 0);
            String strTime = m_realJ05.getDataValue(strBlockName, "sSignaltime", 0);
            String strCount = m_realJ05.getDataValue(strBlockName, "sNowItemCnt", 0);
            String strJobFlag = m_realJ05.getDataValue(strBlockName, "sJobflag", 0);
            String strItemCode = m_realJ05.getDataValue(strBlockName, "sItemCode", 0);
            String strItemName = m_realJ05.getDataValue(strBlockName, "sItemName", 0);
            String strPrice = m_realJ05.getDataValue(strBlockName, "sPrice", 0);
            //String strResult = m_realJ05.getDataValue(strBlockName, "sResult", 0);

            SampleUtil.writeLog(LOG_TAG, String.format("DataSection[%s] PacketCode[%s] Date[%s] Time[%s]",
                    strDataSection, strPacketCode, strDate, strTime));
            SampleUtil.writeLog(LOG_TAG, String.format("Count[%s] JobFlag[%s] Item[%s][%s]", strCount,
                    strJobFlag, strItemCode, strItemName));
            //TRACE.d(LOG_TAG, "[" + strResult + "]");

            CondSignalInfo info = new CondSignalInfo();
            info.m_strTime = strTime;
            info.m_strFlag = strJobFlag;
            info.m_strCount = strCount;
            info.m_strItemCode = strItemCode;
            info.m_strItemName = strItemName;
            info.m_strPrice = strPrice;

            if(m_viewSignalList != null)
                m_viewSignalList.addList(info);
        }
    }

    @Override
    public void onClick(View view)
    {
        int nId = view.getId();

        if(nId == CTRL_ID_QRY_CONDLIST)
            requestCondList();
        else if(nId == CTRL_ID_QRY_ITEMLIST)
            requestItemList();
        else if(nId == CTRL_ID_RESET_REALLIST)
        {
            if(m_viewSignalList != null)
                m_viewSignalList.clearList();
        }
    }

    // 조건리스트 스크롤 끝 이벤트
    @Override
    public void onCondInfoScrollEnd() {

    }

    // 조건리스트 클릭 이벤트 처리
    @Override
    public void onCondInfoClicked(CondSearchInfo infoCond) {
        selectCondSearchInfo(infoCond);

        requestItemList();
    }

    @Override
    public void onCondItemScrollEnd() {

    }

    @Override
    public void onCondItemClicked(CondItemInfo infoCond) {

    }

    @Override
    public void onFIDSelectionChanged(ArrayList<String> arrList) {

        requestItemList();
    }
}
