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

import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

import jp.agentec.abook.abv.bl.acms.client.json.content.ContentJSON;
import jp.agentec.abook.abv.bl.common.Constant;
import jp.agentec.abook.abv.bl.common.constant.ABookKeys;
import jp.agentec.abook.abv.bl.common.exception.ExceptionHandler;
import jp.agentec.abook.abv.bl.common.log.Logger;
import jp.agentec.abook.abv.bl.download.ContentZipDownloadNotification;
import jp.agentec.abook.abv.bl.dto.CategoryContentDto;
import jp.agentec.abook.abv.bl.dto.ContentDto;
import jp.agentec.abook.abv.bl.logic.AbstractLogic;
import jp.agentec.abook.abv.bl.logic.OperationLogic;
import jp.agentec.abook.abv.bl.websocket.MeetingManager;
import jp.agentec.abook.abv.launcher.android.R;
import jp.agentec.abook.abv.ui.common.appinfo.AppDefType;
import jp.agentec.abook.abv.ui.common.constant.ErrorCode;
import jp.agentec.abook.abv.ui.common.constant.ErrorMessage;
import jp.agentec.abook.abv.ui.common.dialog.ABookAlertDialog;
import jp.agentec.abook.abv.ui.common.util.ABVToastUtil;
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.OperationRelatedContentSectionAdapter;
import jp.agentec.abook.abv.ui.home.helper.ActivityHandlingHelper;
import jp.agentec.adf.util.StringUtil;

/**
 * Created by kim, changgyun on 2018/09/10.
 */

public class OperationRelatedContentActivity extends OperationActivity {
    private static final String TAG = "OperationRelatedContentActivity";

    private OperationRelatedContentSectionAdapter mOperationRelatedContentSectionAdapter;

    private ImageView mRefreshButton;
    private ImageButton mOperationHelpButton;

    private TextView mTxtOperationRelatedContent;
    private TextView mTxtOperationName;
    private Button mAllSaveButton;

    private ListView mContentListView;
    private List<CategoryContentDto> mOperationContentList;

    private Long operationId;
    private String operationName;
    private OperationLogic mOperationLogic = AbstractLogic.getLogic(OperationLogic.class);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ac_operation_related_content);

        mOperationHelpButton = (ImageButton) findViewById(R.id.btn_operation_help);

        mTxtOperationName = (TextView) findViewById(R.id.txt_operation_name);
        mAllSaveButton = (Button) findViewById(R.id.btn_all_save);

        mContentListView = (ListView) findViewById(R.id.lv_content_list);

        // 画面下ツールバー
        createCommonToolber();
        // 共通資料ボタン（非活性化）
        mCommonContentButton.setEnabled(false);

        Intent i = getIntent();
        operationId = i.getLongExtra(ABookKeys.OPERATION_ID, 0);
        operationName = i.getStringExtra(ABookKeys.OPERATION_NAME);
        Logger.i(TAG, "operationId=" + operationId + ", operationName=" + operationName);

        mTxtOperationRelatedContent = (TextView) findViewById(R.id.txt_operation_related_content);
        if (operationId == 0) {
            LinearLayout llOperationName = (LinearLayout)  findViewById(R.id.ll_operation_name);
            llOperationName.setVisibility(View.GONE);
            LinearLayout llLine = (LinearLayout)  findViewById(R.id.linear_full_border);
            llLine.setVisibility(View.GONE);
            // リソースパターンの適用
            mTxtOperationRelatedContent.setText("" + PatternStringUtil.patternToString(getApplicationContext(),
                                                        R.string.title_common_content,
                                                        getUserPref(AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0)));
        } else {
            mTxtOperationRelatedContent.setText("" + PatternStringUtil.patternToString(getApplicationContext(),
                                                        R.string.operation_related_content,
                                                        getUserPref(AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0)));
        }

        mTxtOperationName.setText(operationName);
        mAllSaveButton.setVisibility(View.GONE);

        setOnButtonEvent();

    }

    @Override
    public void onDownloadingContentZip(final ContentZipDownloadNotification notification) {
        super.onDownloadingContentZip(notification);

        ContentDto contentDto = null;
        for (CategoryContentDto categoryContentDto : mOperationContentList) {
            for (ContentDto dto : categoryContentDto.contentDtoArray) {
                if (dto.contentId == notification.getContentId()) {
                    contentDto = dto;
                    setDtoDownloadStatus(dto, notification);
                    break;
                }
            }
        }

        if (contentDto != null) {
            updateViewStatus(contentDto);
            updateViewSaveAll();
        }

    }

    private void setDtoDownloadStatus(ContentDto contentDto, ContentZipDownloadNotification notification) {
        contentDto.downloadingFlg = true;
        contentDto.isChecked = false;

        switch (notification.getDownloadStatus()) {
            case Waiting: //リソースダウンロード待機中
            case AutoPaused:
                break;
            case Downloading://リソースダウンロード中
                contentDto.downloadProgress = (int) notification.getDownloadRate();
                break;
            case Paused://リソースダウンロード一時停止
                contentDto.downloadProgress = (int) notification.getDownloadRate();
                break;
            case Initializing://初期化中
                contentDto.downloadProgress = 100;
                break;
            case Succeeded://成功
                try {
                    ContentDto content = contentDao.getContent(notification.getContentId());
                    contentDto.contentId = content.contentId;
                    contentDto.contentName = content.contentName;
                    contentDto.contentNameKana = content.contentNameKana;
                    contentDto.contentDetail = content.contentDetail;
                    contentDto.allPageNum = content.allPageNum;
                    contentDto.orientation = content.orientation;
                    contentDto.updatedFlg = content.updatedFlg;
                    contentDto.downloadedFlg = content.downloadedFlg;
                    contentDto.downloadingFlg = content.downloadingFlg;
                    contentDto.metaVersion = content.metaVersion;
                    contentDto.resourceVersion = content.resourceVersion;
                    contentDto.deliveryStartDate = content.deliveryStartDate;
                    contentDto.deliveryEndDate = content.deliveryEndDate;
                    contentDto.favoriteFlg = content.favoriteFlg;
                    contentDto.contentProtectedFlg = content.contentProtectedFlg;
                    contentDto.thumbnailNormalPath = content.thumbnailNormalPath;
                    contentDto.thumbnailBigPath = content.thumbnailBigPath;
                    contentDto.pagePath = content.pagePath;
                    contentDto.resourcePath = content.resourcePath;
                    contentDto.contentGroups = content.contentGroups;
                    contentDto.newFlg = content.newFlg;
                    contentDto.readingDate = content.readingDate;
                    contentDto.contentSize = content.contentSize;
                } catch (Exception e) {
                    Logger.e(TAG, "setDtoDownloadStatus failed.", e);
                    ErrorMessage.showErrorMessageToast(getApplicationContext(), ErrorCode.E107);
                }
                break;
            case Failed:
                if (ExceptionHandler.isNoSpaceLeftOnDeviceIOException(notification.getError())) {
                    ErrorMessage.showErrorMessageToast(getApplicationContext(), ErrorCode.STORAGE_ERROR);
                } else {
                    ABVToastUtil.showMakeText(getApplicationContext(), getResources().getString(R.string.download_error), Toast.LENGTH_LONG);
                }
                if (notification.getError() != null) {
                    Logger.e(TAG, notification.getError().toString());
                }
                contentDto.downloadingFlg = false;
                break;
            case Canceled:
                contentDto.downloadingFlg = false;
                break;
            case None:
                break;
            default:
                break;
        }
        contentDto.status = notification.getDownloadStatus().type();

        Logger.d(TAG, "contentId: %s, dlStatus: %s, dlRate:%s, dlSize=%s, fileSize:%s", notification.getContentId(), notification.getDownloadStatus(), notification.getDownloadRate(), notification.getDownloadedSize(), notification.getFileSize());
    }


    public void showOperationRelatedContentList() {
        mOperationContentList = mOperationLogic.getOperationRelatedContent();
        Logger.i(TAG, "count of content=" + mOperationContentList.size());

        // Gridビュー
        mOperationRelatedContentSectionAdapter = new OperationRelatedContentSectionAdapter(this, mOperationContentList, isNormalSize());
        mContentListView.setAdapter(mOperationRelatedContentSectionAdapter);

        mOperationRelatedContentSectionAdapter.setAdapterListener(new OperationRelatedContentSectionAdapter.OperationRelatedContentSectionListener() {
            @Override
            public boolean onContentDownload(long contentId) {
                return contentValidCheckAndDownload(contentId, true);
            }

            @Override
            public void onContentDownloadPause(ContentDto contentDto) {
                contentDownloadPause(contentDto.contentId);
                updateViewStatus(contentDto);
            }

            @Override
            public void onContentDownloadResume(ContentDto contentDto) {
                contentDownloadResume(contentDto);
                updateViewStatus(contentDto);
            }

            @Override
            public void onContentDelete(ContentDto contentDto) {
                showContentDeleteDialog(contentDto);
            }

            @Override
            public void onContentDownloadCancel(ContentDto contentDto) {
                showCancelDownloadDialog(contentDto);
            }

            @Override
            public void onOpenContentView(long contentId) {
                try {
                    ContentDto content = contentDao.getContent(contentId);
                    if (!content.downloadingFlg && content.downloadedFlg) {
                        // 遠隔連動 PDFとオリジナル以外の資料は対象外アラート表示
                        MeetingManager meetingManager = MeetingManager.getInstance();
                        if (meetingManager.isSendable() && !StringUtil.contains(content.contentType, new String[]{ContentJSON.KEY_PDF_TYPE, ContentJSON.KEY_NONE_TYPE})) {
                            showNonTargetMeetingContent();
                            return;
                        }

                        Intent intent = new Intent();
                        intent.putExtra(ABookKeys.OPERATION_ID, operationId);
                        ActivityHandlingHelper.getInstance().checkContentActivity(contentId, 0, intent);
                    }
                } catch (Exception e) {
                    Logger.e(TAG, "onOpenContentView failed.", e);
                    ErrorMessage.showErrorMessageToast(getApplicationContext(), ErrorCode.E107);
                }
            }

        });

        updateViewSaveAll();
    }

    /**
     * 遠隔支援中には対象外の資料のアラート表示
     */
    private void showNonTargetMeetingContent() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                final ABookAlertDialog nonTargetMeetingContentDialog = AlertDialogUtil.createAlertDialog(OperationRelatedContentActivity.this, R.string.app_name);
                nonTargetMeetingContentDialog.setCancelable(false);
                nonTargetMeetingContentDialog.setMessage(R.string.msg_non_target_meeting_content);
                nonTargetMeetingContentDialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int whichButton) {
                        nonTargetMeetingContentDialog.dismiss();
                    }
                });
                nonTargetMeetingContentDialog.show();
            }
        });
    }

    /**　
     * ボタンイベント設定
     */
    private void setOnButtonEvent() {
        // プロジェクトホーム画面へ
//        mOperationHomeButton.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                finish();
//            }
//        });

        // 一括保存
        mAllSaveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final List<CategoryContentDto> listItem = mOperationRelatedContentSectionAdapter.getListItem();
                final List<ContentDto> downloadList = new ArrayList<>();
                new AsyncTask<Void, ContentDto, Void>() {
                    @Override
                    protected Void doInBackground(Void... params) {
                        for (CategoryContentDto categoryContentDto : listItem) {
                            for (ContentDto contentDto : categoryContentDto.contentDtoArray){
                                if (!(contentDto.downloadedFlg && !contentDto.updatedFlg)) {
                                    if (contentValidCheckAndShowMessage(contentDto.contentId, MessageType.TYPE_SHOW_ALERT) == ContentCheckResultType.SUCCESS) {
                                        downloadList.add(contentDto);
                                    }
                                }
                            }
                        }
                        return null;
                    }

                    @Override
                    protected void onPostExecute(Void result) {
                        new AsyncTask<Void, ContentDto, Void>() {
                            @Override
                            protected Void doInBackground(Void... params) {
                                for (ContentDto contentDto : downloadList) {
                                    Logger.i(TAG, "downloading content=" + contentDto.contentName);
                                    contentValidCheckAndDownload(contentDto.contentId, true);
                                }
                                return null;
                            }
                        }.execute();
                    }
                }.execute();
            }
        });
    }

    public void showContentDeleteDialog(final ContentDto contentDto) {
        ABookAlertDialog contentsDeleteDialog = AlertDialogUtil.deleteContentAlertDialog(this);
        contentsDeleteDialog.setNegativeButton(R.string.cancel, null);
        contentsDeleteDialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (contentDelete(contentDto)) {
                    contentDto.downloadedFlg = false;
                    contentDto.downloadingFlg = false;

                    updateViewStatus(contentDto);
                    updateViewSaveAll();
                }
            }
        });
        showAlertDialog(contentsDeleteDialog);
    }

    public void showCancelDownloadDialog(final ContentDto contentDto) {
        // リソースパターンの適用
        ABookAlertDialog cancelDownloadDialog = AlertDialogUtil.createAlertDialog(this,
                PatternStringUtil.patternToInt(getApplicationContext(),
                        R.string.cancel,
                        getUserPref(AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0)),
                PatternStringUtil.patternToInt(getApplicationContext(),
                        R.string.msg_cancel_download,
                        getUserPref(AppDefType.UserPrefKey.RESOURCE_PATTERN_TYPE, 0)));
        cancelDownloadDialog.setNegativeButton(R.string.cancel, null);
        cancelDownloadDialog.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                contentDownloadCancel(contentDto);
                updateViewStatus(contentDto);
            }
        });
        showAlertDialog(cancelDownloadDialog);
    }

    private void updateViewStatus(ContentDto contentDto) {
        final ContentDto updatedContentDto = contentDto;
        handler.post(new Runnable() {
            @Override
            public void run() {
                mOperationRelatedContentSectionAdapter.updateDownloadView(updatedContentDto);
            }
        });
    }

    private void updateViewSaveAll() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                final List<CategoryContentDto> listItem = mOperationRelatedContentSectionAdapter.getListItem();
                int visible = View.GONE;
                for (CategoryContentDto categoryContentDto : listItem) {
                    for (ContentDto dto : categoryContentDto.contentDtoArray) {
                        if (!(dto.downloadedFlg && !dto.updatedFlg)) {
                            visible = View.VISIBLE;
                            break;
                        }
                    }
                }
                mAllSaveButton.setVisibility(visible);
            }
        });
    }

    @Override
    public void onResume() {
        Logger.i(TAG, "onResume:start");
        super.onResume();

        showOperationRelatedContentList();
    }

    public void onClickShowHelpView(View v) {
        if (operationId == 0) {
            showHelpViewDialog(Constant.HelpViewType.CommonContent);
        } else {
            showHelpViewDialog(Constant.HelpViewType.OperationDetail);
        }
    }
}
