package jp.agentec.abook.abv.ui.home.activity;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import java.util.List;

import jp.agentec.abook.abv.bl.acms.type.AcmsApis;
import jp.agentec.abook.abv.bl.common.ABVEnvironment;
import jp.agentec.abook.abv.bl.common.log.Logger;
import jp.agentec.abook.abv.bl.data.ABVDataCache;
import jp.agentec.abook.abv.bl.dto.PushMessageDto;
import jp.agentec.abook.abv.bl.logic.AbstractLogic;
import jp.agentec.abook.abv.bl.logic.PushMessageLogic;
import jp.agentec.abook.abv.launcher.android.R;
import jp.agentec.abook.abv.ui.common.activity.ABVUIActivity;
import jp.agentec.abook.abv.ui.common.appinfo.AppDefType;
import jp.agentec.abook.abv.ui.common.constant.NaviConsts;
import jp.agentec.abook.abv.ui.common.dialog.ABookAlertDialog;
import jp.agentec.abook.abv.ui.common.util.AlertDialogUtil;
import jp.agentec.abook.abv.ui.common.util.PatternStringUtil;
import jp.agentec.abook.abv.ui.home.adapter.PushMessageListAdapter;
import jp.agentec.abook.abv.ui.home.helper.ActivityHandlingHelper;
import jp.agentec.abook.abv.ui.viewer.activity.OnlineHTMLWebViewActivity;
import jp.agentec.adf.util.DateTimeFormat;
import jp.agentec.adf.util.DateTimeUtil;

public class OperationActivity extends ABVUIActivity {
    @SuppressWarnings("unused")
    private static final String TAG = "OperationActivity";
    protected ImageButton mOperationHomeButton;        // ホームボタン
    protected ImageButton mDashboardButton;            // ダッシュボード
    protected ImageButton mCommonContentButton;        // 関連資料
    protected ImageButton mCommunicationButton;        // コミュニケーション
    protected ImageButton mQuickReportPrintButton;     // 簡易帳票印刷ボタン
    private PushMessageLogic mPushMessageLogic = AbstractLogic.getLogic(PushMessageLogic.class);
    private Dialog mCommunicationMenuDialog;
    private Dialog mSubMenuDialog;
    private Dialog mPushMessageListDialog;
    private ListView mPushMessageListView;
    private PushMessageListAdapter mPushMessageListAdapter;
    protected void createCommonToolber() {
        // ホームボタン
        mOperationHomeButton = findViewById(R.id.btn_operation_home);
        mOperationHomeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                backHome();
            }
        });

        // ダッシュボード
        mDashboardButton = findViewById(R.id.btn_operation_dashboard);
        mDashboardButton.setEnabled(true);
        mDashboardButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showDashboard();
            }
        });

        // 共通資料
        mCommonContentButton = findViewById(R.id.btn_common_content);
        mCommonContentButton.setEnabled(true);
        mCommonContentButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCommonContent();
            }
        });

        // コミュニケーション
        mCommunicationButton = findViewById(R.id.btn_communication_menu);
        mCommunicationButton.setImageDrawable(getRDrawable(R.drawable.ic_communication_menu));
        mCommunicationButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCommunicationMenuDialog();
            }
        });

        // 簡易帳票印刷ボタン
        mQuickReportPrintButton = findViewById(R.id.btn_operation_print);
        if (ABVDataCache.getInstance().serviceOption.isUnableIOReport()) {
            mQuickReportPrintButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    showPrintTargetSelect();
                }
            });
            mQuickReportPrintButton.setVisibility(View.VISIBLE);
        } else {
            findViewById(R.id.print_layout).setVisibility(View.GONE);
            mQuickReportPrintButton.setVisibility(View.GONE);
        }
    }

    private void  backHome() {
        Intent intent = new Intent();
        intent.setClass(this, OperationListActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
    }

    //  ダッシュボード表示
    private void showDashboard() {
        Intent intent = new Intent();
        intent.setClass(this, DashboardActivity.class);
        startActivity(intent);
    }
    // 共通資料画面表示
    private void showCommonContent() {
        Intent intent = new Intent();
        intent.setClass(this, OperationRelatedContentActivity.class);
        startActivity(intent);
    }
    /**
     * コミュニケーションダイアログの表示
     */
    private void showCommunicationMenuDialog() {
        mCommunicationMenuDialog = new Dialog(OperationActivity.this);
        mCommunicationMenuDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mCommunicationMenuDialog.setCanceledOnTouchOutside(false);
        mCommunicationMenuDialog.setContentView(R.layout.communication_menu_dialog);

        List<PushMessageDto> pushMessageDtoList = mPushMessageLogic.getAllPushMessageList();
        LinearLayout ll_menuItem_meeting = mCommunicationMenuDialog.findViewById(R.id.ll_item_meeting);
        ll_menuItem_meeting.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivityHandlingHelper.getInstance().startMeetingActivity();
                mCommunicationMenuDialog.dismiss();
            }
        });

        mCommunicationMenuDialog.findViewById(R.id.close_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCommunicationMenuDialog.dismiss();
            }
        });

        mCommunicationMenuDialog.show();
    }

    // 設定画面へ遷移
    public void onClickSetting(View v) {
        mSubMenuDialog = new Dialog(OperationActivity.this);
        mSubMenuDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mSubMenuDialog.setCanceledOnTouchOutside(false);
        mSubMenuDialog.setContentView(R.layout.operation_list_submenu_dialog);
        mSubMenuDialog.findViewById(R.id.ll_setting).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSubMenuDialog.dismiss();
                showSetting();
            }
        });
        mSubMenuDialog.findViewById(R.id.ll_push_message_list).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mSubMenuDialog.dismiss();
                showPushMessageListDialog();
            }
        });
        mSubMenuDialog.findViewById(R.id.close_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mSubMenuDialog.dismiss();
            }
        });

        mSubMenuDialog.show();
    }

    /**
     * インターネットが繋がってない場合のダイアログ表示
     */
    protected void showDisConnectNetworkDialog() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                // ヘッダーの新着更新処理を完了にさせる
                stopUpdateAnimation();
                final ABookAlertDialog messageDialog = AlertDialogUtil.createAlertDialog(OperationActivity.this, R.string.app_name);
                messageDialog.setMessage(getString(R.string.msg_network_offline));
                messageDialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int whichButton) {
                        messageDialog.dismiss();
                    }
                });
                messageDialog.show();
            }
        });
    }

    /**
     * 簡易帳票印刷対象選択画面表示
     */
    protected void showPrintTargetSelect() {
        if (!ABVEnvironment.getInstance().networkAdapter.isNetworkConnected()) {
            showDisConnectNetworkDialog();
            return;
        }
        Intent intent = new Intent();
        intent.setClass(OperationActivity.this, OnlineHTMLWebViewActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        intent.putExtra("LINKURL", AcmsApis.getApiUrl(ABVEnvironment.getInstance().acmsAddress, ABVDataCache.getInstance().getUrlPath(), AcmsApis.ApiQuickReportSearch));
        startActivity(intent, NaviConsts.Right);
    }

    /**
     * プッシュメッセージ一覧画面表示
     */
    protected void showPushMessageListDialog(){
        mPushMessageListDialog = new Dialog(OperationActivity.this);
        mPushMessageListDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        mPushMessageListDialog.setCanceledOnTouchOutside(false);
        mPushMessageListDialog.setContentView(R.layout.push_message_list_dialog);
        mPushMessageListView = (ListView) mPushMessageListDialog.findViewById(R.id.lv_push_message);

        List<PushMessageDto> pushMessageDtoList = mPushMessageLogic.getAllPushMessageList();
        mPushMessageListAdapter = new PushMessageListAdapter(OperationActivity.this, pushMessageDtoList);
        mPushMessageListView.setAdapter(mPushMessageListAdapter);

        mPushMessageListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                PushMessageDto pushMessageDto = (PushMessageDto)adapterView.getItemAtPosition(i);
                showPushMessageDetailView(pushMessageDto);
            }
        });

        mPushMessageListView.invalidate();
        mPushMessageListView.setClickable(false);
        TextView notesTextView = mPushMessageListDialog.findViewById(R.id.tv_notes);
        notesTextView.setText(R.string.msg_push_message_list_notes);

        mPushMessageListDialog.findViewById(R.id.back_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                List<PushMessageDto> pushMessageDtoList = mPushMessageLogic.getAllPushMessageList();
                mPushMessageListAdapter.setItem(pushMessageDtoList);
                showPushMessgeListView(true);
            }
        });

        mPushMessageListDialog.findViewById(R.id.close_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPushMessageListDialog.dismiss();
                reloadOperationPushMessageListView();
            }
        });

        showPushMessgeListView(true);
        mPushMessageListDialog.show();
    }

    /**
     * プッシュメッセージ詳細画面表示
     * @param dto プッシュメッセージ情報
     */
    private void showPushMessageDetailView(final PushMessageDto dto) {
        TextView detailNotesTextVie = (TextView)mPushMessageListDialog.findViewById(R.id.tv_detail_notes);
        int errorMessageResourceId = 0;
        if (!dto.readingFlg) {
            if (ABVEnvironment.getInstance().networkAdapter.isNetworkConnected()) {
                //サーバ通信
                showProgressPopup(PatternStringUtil.patternToString(getApplicationContext(),
                        R.string.msg_common_processing,
                        getUserPref(AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0)));
                try {
                    if (mPushMessageLogic.sendReadPushMessage(dto.pushMessageId)) {
                        mPushMessageLogic.updateReadingFlg(dto.pushMessageId);
                    } else {
                        Logger.e(TAG,"sendReadPushMessage result false");
                        errorMessageResourceId = R.string.msg_push_message_detail_api_error;
                    }
                } catch (Exception e) {
                    Logger.e(TAG,"e.getLocalizedMessage = " + e.getLocalizedMessage());
                    errorMessageResourceId = R.string.msg_push_message_detail_api_error;
                } finally {
                    closeProgressPopup();
                }
            } else {
                errorMessageResourceId = R.string.msg_push_message_detail_api_disconnect;
            }
        }
        if (errorMessageResourceId == 0) {
            detailNotesTextVie.setVisibility(View.GONE);
            detailNotesTextVie.setText(null);
        } else {
            detailNotesTextVie.setVisibility(View.VISIBLE);
            detailNotesTextVie.setText(errorMessageResourceId);
        }
        TextView messageTextView = (TextView)mPushMessageListDialog.findViewById(R.id.tv_message);
        TextView sendDateTextView = (TextView)mPushMessageListDialog.findViewById(R.id.tv_send_date);
        TextView sendOperationNameTextView = (TextView)mPushMessageListDialog.findViewById(R.id.tv_operation_name);
        messageTextView.setText(dto.pushMessage);
        sendDateTextView.setText(DateTimeUtil.toString(dto.pushSendDate, DateTimeFormat.yyyyMMddHHmm_slash));
        sendOperationNameTextView.setText(dto.operationName);
        showPushMessgeListView(false);
    }

    /**
     * プッシュメッセージ一覧・詳細画面の切り替え処理
     * @param pushMessageListViewFlg true:一覧, false:詳細
     */
    private void showPushMessgeListView(boolean pushMessageListViewFlg) {
        TextView titleTextView = (TextView)mPushMessageListDialog.findViewById(R.id.tv_toolbar_title);
        if (pushMessageListViewFlg) {
            mPushMessageListDialog.findViewById(R.id.ll_push_message_list).setVisibility(View.VISIBLE);
            mPushMessageListDialog.findViewById(R.id.close_btn).setVisibility(View.VISIBLE);
            mPushMessageListDialog.findViewById(R.id.back_btn).setVisibility(View.GONE);
            mPushMessageListDialog.findViewById(R.id.ll_detail).setVisibility(View.GONE);
            // リソースパターンの適用
            titleTextView.setText(PatternStringUtil.patternToString(getApplicationContext(),
                    R.string.push_message_list,
                    getUserPref(AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0)));
        } else {
            mPushMessageListDialog.findViewById(R.id.ll_push_message_list).setVisibility(View.GONE);
            mPushMessageListDialog.findViewById(R.id.close_btn).setVisibility(View.VISIBLE);
            mPushMessageListDialog.findViewById(R.id.back_btn).setVisibility(View.VISIBLE);
            mPushMessageListDialog.findViewById(R.id.ll_detail).setVisibility(View.VISIBLE);
            // リソースパターンの適用
            titleTextView.setText(PatternStringUtil.patternToString(getApplicationContext(),
                    R.string.title_message_detail,
                    getUserPref(AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0)));
        }
    }

    /**
     * 子クラスから実装（未読プッシュメッセージ表示領域をリロード）
     */
    protected void reloadOperationPushMessageListView(){}
}
