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

import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import androidx.core.app.ActivityCompat;
import android.view.View;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import jp.agentec.abook.abv.bl.common.log.Logger;
import jp.agentec.abook.abv.bl.data.dao.AbstractDao;
import jp.agentec.abook.abv.bl.data.dao.ContentDao;
import jp.agentec.abook.abv.bl.download.ContentDownloader;
import jp.agentec.abook.abv.bl.dto.MemberInfoDto;
import jp.agentec.abook.abv.bl.logic.AbstractLogic;
import jp.agentec.abook.abv.bl.logic.UserAuthenticateLogic;
import jp.agentec.abook.abv.cl.util.PreferenceUtil;
import jp.agentec.abook.abv.launcher.android.R;
import jp.agentec.abook.abv.ui.common.appinfo.AppDefType;
import jp.agentec.abook.abv.ui.home.activity.LoginActivity;
import jp.agentec.abook.abv.ui.home.helper.ABookPermissionHelper;

/**
 * スプラッシュActivityのクラスです。
 * 
 * @author Minhyuk Seok
 * @version 1.1.1
 * 
 */

public abstract class ABVSplashActivity extends ABVNoAuthenticatedActivity {
	final static String TAG = "ABVSplashActivity";

	protected ContentDao contentDao = AbstractDao.getDao(ContentDao.class);
	protected ContentDownloader contentDownloader = ContentDownloader.getInstance();
	private ArrayList<String>mPermissionArray = new ArrayList();
	protected static final int REQUEST_PERMISSIONS = 1001;

	/** Called when the activity is first created. */
	@Override
    public void onCreate(Bundle savedInstanceState) {
		Logger.i(TAG, "onCreate");
		super.onCreate(savedInstanceState);
		//コンテンツビューからコンテンツビューへ戻る時用で保存したデータ初期化
		getABVUIDataCache().resetReturnContentIdList();

		setContentView(R.layout.ac_splash1);
		getABVUIDataCache().isFirstLaunching = true;
	}

	@Override
	protected void onResume() {
		super.onResume();
		boolean checkFlg = PreferenceUtil.getUserPref(this, AppDefType.UserPrefKey.ALL_PERMISSION_CHECK, true);
		ABookPermissionHelper helper = new ABookPermissionHelper(this);
		if (checkFlg) {
			PreferenceUtil.putUserPref(this, AppDefType.UserPrefKey.ALL_PERMISSION_CHECK, false);
			mPermissionArray = helper.checkMultiPermissions();
		} else {
			mPermissionArray = helper.checkAndroidVersionUpPermissions();
		}
		commonCheckPermission();
	}
	/**
	 * 権限チェック後、画面表示
	 */
	private void commonCheckPermission() {
		if (mPermissionArray.size() == 0) {
			abookMode();
		} else {
			ActivityCompat.requestPermissions(this,
					mPermissionArray.toArray(new String[mPermissionArray.size()]),
					REQUEST_PERMISSIONS);
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

    @Override
	protected View getContentViewId() {
		return null;
	}

	@Override
	protected void onPasswordChanged() {
		abookMode();
	}

	@Override
	protected void onApplicationBroughtFromBackground() {
	}

	private void abookMode() {
		// Activityを終了するかしないか
		boolean finishActivityFlag = true;

		try {
			UserAuthenticateLogic logic = AbstractLogic.getLogic(UserAuthenticateLogic.class);
			MemberInfoDto memberInfo = logic.getMemberInfo();

			loadAddressIfSaasGeneral();
			// 通常ログインの場合
			if (memberInfo == null) {
				// ログイン画面へ遷移する
				callLoginActivity(false, false, false);
			} else {
				// 一定期間経過後強制ログアウトチェック
				if (!checkForceOfflineLogout()) {
					// 最後のログインから90日のチェック
					if (!checkValidAuthTime()) {
						// キャンセルした場合のイベントリスナ
						OnClickListener cancelListener = new OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								startLogoAnimation();
							}
						};
						// パスワード定期変更チェック
						if (checkRequiredChangePassword(cancelListener)) {
							finishActivityFlag = false;
						} else {
							finishActivityFlag = false;
							startLogoAnimation();
						}
					}
				}
			}

		} catch (Exception e) {
			Logger.e("ABVException Login", e);
			Intent intent = new Intent();
			intent.setClassName(getApplicationContext().getPackageName(), LoginActivity.class.getName()).setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
			startActivity(intent);
		} finally {
			if (finishActivityFlag) {
				finish();
			}
		}
	}

	private void copyFile(InputStream in, OutputStream out) throws IOException {
		byte[] buffer = new byte[1024];
		int read;
		while ((read = in.read(buffer)) != -1) {
			out.write(buffer, 0, read);
		}
	}
	
	@Override
    protected void goNext() {
		startLogoAnimation();
	}
}
