package com.eugenefn.openapi.sample;

import java.util.ArrayList;

import com.eugenefn.openapi.intrf.INetInitListener;
import com.eugenefn.openapi.intrf.INetLoginListener;
import com.eugenefn.openapi.intrf.INetLogoutListener;
import com.eugenefn.openapi.proc.SmartChampDefs;
import com.eugenefn.openapi.proc.SmartChampAPI;
import com.eugenefn.openapi.sample.view.SampleMenuView;
import com.eugenefn.openapi.sample.view.SampleIntroView;
import com.eugenefn.openapi.sample.view.util.SampleUtil;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;

import android.view.ViewGroup.LayoutParams;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

@SuppressLint("NewApi")
public class SampleActivity
extends Activity
implements INetInitListener, INetLoginListener, INetLogoutListener
{
	private static final int REQUEST_INIT_PERM = 1;

	private SampleFrameView		m_viewFrame = null;

	private SampleIntroView		m_viewIntro = null;
	private SampleMenuView m_viewMenu = null;
	
	ArrayList<String> m_arrAccount = null;				//계좌리스트
	ArrayList<String> m_arrAccountName = null;		//계좌명 리스트
	ArrayList<String> m_arrAccountCode = null;		//상품코드 리스트

	private long m_nLastBackPressed = 0;

	private String m_strDevMode = SmartChampDefs.SERVER_MODE_DEFAULT;

	/* Called when the activity is first created. */
	@Override
	public void onCreate( Bundle savedInstanceState )
	{
		super.onCreate( savedInstanceState );
		
		m_arrAccount = new ArrayList<String>();
		m_arrAccountName = new ArrayList<String>();
		m_arrAccountCode = new ArrayList<String>();
		
		m_viewFrame = new SampleFrameView(this, this);
		m_viewFrame.setLayoutParams( new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT ) );
		m_viewFrame.setBackgroundColor( Color.rgb( 0, 0, 0 ) );
		
		showIntroView();

		m_strDevMode = SampleUtil.getConfig(this, "dev_mode", SmartChampDefs.SERVER_MODE_DEFAULT);

		setContentView(m_viewFrame);	
		
		checkPermission();
	}

	@Override
	protected void onResume()
	{
		super.onResume();

//		// 앱이 중지상태에서 올라온 경우, 필요한 작업을 수행하게 함
//		if(SmartChampAPI.getInstance() != null)
//		{
//			SmartChampAPI.getInstance().setAppActivated(this, 1);
//		}
	}

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

		// 앱이 중지된 경우, api에도 알려 중지중에 다른 작업을 안하게 함
//		if(SmartChampAPI.getInstance() != null)
//		{
//			SmartChampAPI.getInstance().setAppActivated(this, -1);
//		}
	}

	@Override
	public void onDestroy()
	{
		super.onDestroy();
		
		if(m_viewFrame != null)
		{
			m_viewFrame.releaseView();
			m_viewFrame = null;
		}

		if(m_viewMenu != null)
		{
			m_viewMenu.releaseView();
			m_viewMenu = null;
		}	
		
		if(m_arrAccount != null)
		{
			m_arrAccount.clear();
			m_arrAccount = null;
		}
		
		if(m_arrAccountName != null)	
		{
			m_arrAccountName.clear();
			m_arrAccountName = null;
		}
	
		if(m_arrAccountName != null)	
		{		
			m_arrAccountCode.clear();
			m_arrAccountCode = null;
		}
		
		/**
		 * Open API 종료...
		 */
		SmartChampAPI.releaseOpenAPI();
	}

	@Override
	public void onBackPressed()
	{
		if(m_viewFrame.onBackPressed()) return;

		long nCurrent = System.currentTimeMillis();
		if((nCurrent - m_nLastBackPressed) > 2000)
		{
			Toast.makeText(this, "뒤로버튼을 한번더 누르면 종료합니다.", Toast.LENGTH_SHORT).show();
			m_nLastBackPressed = nCurrent;
			return;
		}

		super.onBackPressed();

		terminateApp();
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
	{
		//super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		if(requestCode == REQUEST_INIT_PERM)
		{
			for(int i = 0; i < grantResults.length; i++)
			{
				if(grantResults[i] != PackageManager.PERMISSION_GRANTED)
				{
					Toast.makeText(this, "필수권한이 허용되어야 앱 실행이 가능합니다.", Toast.LENGTH_SHORT).show();
					terminateApp();
					return;
				}
			}

			initApp();
		}
	}

	// 앱 권한 체크
	private void checkPermission()
	{
		if (
				ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED ||
				ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_NUMBERS) != PackageManager.PERMISSION_GRANTED ||
				ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
				ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
		{
			if (
					ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE) ||
					ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_NUMBERS) ||
					ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE) ||
					ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE))
			{
				ActivityCompat.requestPermissions(this, new String[]{
								Manifest.permission.READ_PHONE_STATE,
								Manifest.permission.READ_PHONE_NUMBERS,
								Manifest.permission.READ_EXTERNAL_STORAGE,
								Manifest.permission.WRITE_EXTERNAL_STORAGE},
						REQUEST_INIT_PERM);
			}
			else
			{
				ActivityCompat.requestPermissions(this, new String[]{
								Manifest.permission.READ_PHONE_STATE,
								Manifest.permission.READ_PHONE_NUMBERS,
								Manifest.permission.READ_EXTERNAL_STORAGE,
								Manifest.permission.WRITE_EXTERNAL_STORAGE},
						REQUEST_INIT_PERM);
			}
		}
		else
		{
			initApp();
		}
	}

	// 기본 셋팅
	private void initApp()
	{
		// 서버 접속모드 지정, api 초기화 전에 호출해야 함
		String strDevMode = SampleUtil.getConfig(this, "dev_mode", SmartChampDefs.SERVER_MODE_DEFAULT);
		SmartChampAPI.setDevMode(strDevMode);

		// 초기화
		SmartChampAPI.initOpenAPI(this);

		//Listener 셋팅
		SmartChampAPI.getInstance().setInitListener(this);
		SmartChampAPI.getInstance().setLoginListener(this);
		SmartChampAPI.getInstance().setLogoutListener(this);

		SmartChampAPI.getInstance().startConnect();
	}

	private void terminateApp()
	{
		finish();
	}

	@Override
	public void onSessionConnecting() {
		//Toast.makeText(this, "서버 접속 시작.", Toast.LENGTH_SHORT ).show();
		if(m_viewIntro != null)
			m_viewIntro.setInfoText("서버에 접속합니다.");
	}

	@Override
	public void onSessionConnected(boolean isSuccess, String strErrorMsg) {
		//서버 성공
		if(isSuccess == true)
		{
			if(m_viewIntro != null)
				m_viewIntro.setInfoText("서버 접속 성공");
		}
		else//서버 실패
		{
			Toast.makeText(this, strErrorMsg, Toast.LENGTH_SHORT ).show();

			if(m_viewIntro != null)
				m_viewIntro.setInfoText("서버 접속 실패");
		}
	}
	
	@Override
	public void onAPIVersionState(int nCheckState, String strMessage)
	{
		//Toast.makeText(this, "라이브러리 버젼체크 완료.", Toast.LENGTH_SHORT ).show();
		if(nCheckState < 0)
		{
			// 버전체크 실패 (서비스 오류) (앱 중지)
		} else if(nCheckState == 0)
		{
			// 정상
		} else if(nCheckState == 1)
		{
			// 버전 업그레이드 필요 (정상)

		} else if(nCheckState == 2)
		{
			// 버전 업그레이드 필수 (앱 중지)
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("안내");
			builder.setMessage("유진 SmartChamp OpenAPI 업그레이드가 필요합니다.\n\n" + strMessage);
			builder.setNeutralButton("확인 ", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
				@Override
				public void onDismiss(DialogInterface dialog) {
					SampleActivity.this.terminateApp();
				}
			});
			builder.show();
		}
	}
		
	@Override
	public void onUpdateDownloadState(int nState, int nIndex, int nCount, String sMessage)
	{
		if(nState == 0)
		{
			// 진행 상태
			// nIndex = 0, nCount = 0 : 준비작업
			// nCount > 0 ? 다운로드 진행
		} else if(nState == 1)
		{
			// 안내메시지
		} else if(nState == 2)
		{
			// 작업 완료
		}

		if(m_viewIntro != null)
			m_viewIntro.updateProgress(nState, nIndex, nCount, sMessage);
	}

	@Override
	public void onMasterLoadState(int nState)
	{
		//Toast.makeText(this, "Master 파일 Loading...", Toast.LENGTH_SHORT ).show();
		if(m_viewIntro != null)
			m_viewIntro.setInfoText("필요한 파일 로드 완료");
	}
	
	@Override
	public void onInitFinished()
	{
		/**
		 * 로그인View를 생성 하고 클릭 이벤트 지정
		 */

		// 메뉴 선택창
		showMenuView();

//		int nLoginType = SmartChampAPI.getInstance().getLoginType();
//
//		if(nLoginType == SmartChampDefs.LOGIN_TYPE_NONE)
//		{
//			// 로그아웃 상태거나, 한번도 로그인 하지 않았으면... 로그인 창 표시
//			if(m_viewFrame != null)
//				m_viewFrame.showLoginDialog();
//		}
	}

	@Override
	public void onRequiredRefresh(int nReason)
	{
		if(m_viewFrame != null)
			m_viewFrame.onRefreshView();

		if(nReason == SmartChampDefs.REFRESH_REASON_RECONNECT) {
			Toast.makeText(getBaseContext(), "재접속 되었습니다.", Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public void onRequestedTerminate() {
		Toast.makeText(this, "접속이 종료됩니다.", Toast.LENGTH_SHORT).show();

		terminateApp();
	}

	@Override
	public void onLoginStarted()
	{
		if(m_viewFrame != null)
			m_viewFrame.showProgress("로그인 중 입니다.");
	}
	
	@Override
	public void onLoginResult(boolean isSuccess, String strErrorMsg)
	{
		if(m_viewFrame != null)
			m_viewFrame.hideProgress();
		
		if(isSuccess == true )
		{
			Toast.makeText( getBaseContext(), "로그인 성공", Toast.LENGTH_SHORT ).show();

			if(m_viewFrame != null) {
				m_viewFrame.hideLoginDialog();
				m_viewFrame.onRefreshView();
			}

			// 로그인 성공한 아이디 저장
			SampleUtil.setConfig(this, "login.userid", SmartChampAPI.getInstance().getLoginUserID());
		} else {
			Toast.makeText( getBaseContext(), strErrorMsg, Toast.LENGTH_SHORT ).show();

			m_viewFrame.onRefreshView();
		}
	}

	@Override
	public void onLogoutFinished()
	{
		Toast.makeText(getBaseContext(), "로그아웃 완료", Toast.LENGTH_SHORT).show();

		if(m_viewFrame != null) {
			m_viewFrame.onRefreshView();

			m_viewFrame.showLoginDialog();
		}
	}

	public void showIntroView()
	{
		if(m_viewIntro != null)
		{
			m_viewIntro.releaseView();
			m_viewIntro = null;
		}

		m_viewIntro = new SampleIntroView(this);
		m_viewIntro.initView();
		
		m_viewIntro.setBackgroundColor(Color.rgb(255, 255, 255));
		
		m_viewFrame.setView(m_viewIntro);
	}
	
	public void showMenuView()
	{
		if(m_viewMenu != null)
		{
			m_viewMenu.releaseView();
			m_viewMenu = null;
		}	

		m_viewMenu = new SampleMenuView(this);
		m_viewMenu.initView(this);

		m_viewFrame.setView(m_viewMenu);
	}

}
