package com.eugenefn.openapi.sample.view;

import com.eugenefn.openapi.proc.SmartChampDefs;
import com.eugenefn.openapi.proc.SmartChampAPI;
import com.eugenefn.openapi.sample.view.screen.CondSearchView;
import com.eugenefn.openapi.sample.view.screen.FutOptSiseView;
import com.eugenefn.openapi.sample.view.screen.SiseBaseView;
import com.eugenefn.openapi.sample.view.screen.StockSiseView;
import com.eugenefn.openapi.sample.view.screen.QueryTestView;
import com.eugenefn.openapi.sample.view.screen.WStockSiseView;
import com.eugenefn.openapi.sample.view.util.LayoutUtil;
import com.eugenefn.openapi.sample.SampleActivity;
import com.eugenefn.openapi.sample.view.util.SampleUtil;
import com.eugenefn.openapi.sample.view.view.UserInfoView;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class SampleMenuView
extends SampleBaseView
implements View.OnClickListener
{
	private static final String LOG_TAG = "메뉴 화면";
	
	private String m_arrMenus [] = { "국내주식", "선물옵션", "해외주식", "조건검색" , "TR테스트" };
	private Class m_arrScreen[] = { StockSiseView.class, FutOptSiseView.class,
			WStockSiseView.class, CondSearchView.class, QueryTestView.class };
	private int m_arrMenuAuth[] = { SmartChampDefs.LOGIN_TYPE_AUTO,
			SmartChampDefs.LOGIN_TYPE_AUTO, SmartChampDefs.LOGIN_TYPE_AUTO,
			SmartChampDefs.LOGIN_TYPE_AUTO, SmartChampDefs.LOGIN_TYPE_AUTO };

	// 레이아웃 구성
	private int					TITLE_HEIGHT = 60;
	private int					BUTTON_WIDTH = 200;
	private int					BUTTON_HEIGHT = 50;
	private int					PADDING_H = 10;
	private int					PADDING_V = 10;

	private int CTRL_ID_CHANGESERVER = 10;

	private int CTRL_ID_LOGIN = 11;
	private int CTRL_ID_LOGOUT = 12;
	private int CTRL_ID_MENU_START = 100;

	private SiseBaseView		m_viewCurrent = null;

	private UserInfoView		m_viewUserInfo;

	private Button				m_buttonLogin;
	private Button				m_buttonLogout;

	private Activity			m_activity;

	public SampleMenuView(Context context)
	{
		super(context);
	
		setBackgroundColor(Color.WHITE);
		
		TITLE_HEIGHT = (int)SampleUtil.dipToPixels(context, 60);

		BUTTON_WIDTH = (int)SampleUtil.dipToPixels(context, 130);
		BUTTON_HEIGHT = (int)SampleUtil.dipToPixels(context, 50);

		PADDING_H = (int)SampleUtil.dipToPixels(context, 10);
		PADDING_V = (int)SampleUtil.dipToPixels(context, 10);
	}
	
	//화면 초기화
	public void initView( SampleActivity actMain)
	{
		m_activity = actMain;

		LinearLayout layoutFrame = new LinearLayout(getContext());
		layoutFrame.setOrientation(LinearLayout.VERTICAL);
		layoutFrame.setPadding(PADDING_H*2, PADDING_V * 2, PADDING_H*2, PADDING_V);

		TextView viewVersion = LayoutUtil.makeTextView(getContext(), " ※ 샘플 버전 : " + SampleUtil.getVersionInfo(getContext()) + "  ---  " + "API 버전 : " + SmartChampAPI.getInstance().getAPIVersion());
		layoutFrame.addView(viewVersion, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, TITLE_HEIGHT));

		String strDevMode = SampleUtil.getConfig(getContext(), "dev_mode", SmartChampDefs.SERVER_MODE_DEFAULT);

		Button buttonChangeServer = LayoutUtil.makeCtrlButton(getContext(), CTRL_ID_CHANGESERVER, strDevMode.equals(SmartChampDefs.SERVER_MODE_DEV) ? "운영서버로 변경" : "개발서버로 변경");
		buttonChangeServer.setOnClickListener(this);
		TextView viewChange = LayoutUtil.makeTextView(getContext(), " ※ 접속서버 : " + (strDevMode.equals(SmartChampDefs.SERVER_MODE_DEV) ? "개발서버" : "운영서버"));
		LinearLayout layoutChange = new LinearLayout(getContext());
		layoutChange.setOrientation(LinearLayout.HORIZONTAL);

		layoutChange.addView(viewChange, new LinearLayout.LayoutParams(0, LayoutParams.WRAP_CONTENT, 1));
		layoutChange.addView(buttonChangeServer, new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));

		layoutFrame.addView(layoutChange, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, TITLE_HEIGHT));

		TextView viewTitle = LayoutUtil.makeTextView(getContext(), " ※ 선택하세요");
		layoutFrame.addView(viewTitle, new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, TITLE_HEIGHT));

		LinearLayout layoutMenus = new LinearLayout(getContext());
		layoutMenus.setOrientation(LinearLayout.VERTICAL);

		for(int i = 0; i < m_arrMenus.length; i += 2)
		{
			LinearLayout layoutRow = new LinearLayout(getContext());
			layoutRow.setOrientation(LinearLayout.HORIZONTAL);
			layoutRow.setGravity(Gravity.CENTER);

			Button button = LayoutUtil.makeCtrlButton(getContext(), CTRL_ID_MENU_START + i, m_arrMenus[i]);
			button.setOnClickListener(this);
			LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(BUTTON_WIDTH, BUTTON_HEIGHT);
			param.rightMargin = PADDING_H;
			layoutRow.addView(button, param);

			LinearLayout.LayoutParams param2 = new LinearLayout.LayoutParams(BUTTON_WIDTH, BUTTON_HEIGHT);
			param.leftMargin = PADDING_H;

			if((i + 1) < m_arrMenus.length)
			{
				Button button2 = LayoutUtil.makeCtrlButton(getContext(), CTRL_ID_MENU_START + i + 1, m_arrMenus[i + 1]);
				button2.setOnClickListener(this);
				layoutRow.addView(button2, param2);
			} else {
				layoutRow.addView(new View(getContext()), param2);
			}

			LinearLayout.LayoutParams paramRow = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
			paramRow.topMargin = PADDING_V;
			layoutMenus.addView(layoutRow, paramRow);
		}

		LinearLayout.LayoutParams paramMenus = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		paramMenus.gravity = Gravity.CENTER_HORIZONTAL;
		//paramMenus.setMargins(0, PADDING_V, 0, 0);
		layoutFrame.addView(layoutMenus, paramMenus);

		LinearLayout layoutLogin = new LinearLayout(getContext());
		layoutLogin.setOrientation(LinearLayout.HORIZONTAL);

		// 사용자 정보
		TextView viewTitle2 = LayoutUtil.makeTextView(getContext(), " ※ 사용자 정보");
		LinearLayout.LayoutParams param3 = new LinearLayout.LayoutParams(0, TITLE_HEIGHT, 1);
		layoutLogin.addView(viewTitle2, param3);

		m_buttonLogin = LayoutUtil.makeCtrlButton(getContext(), CTRL_ID_LOGIN, "로그인");
		m_buttonLogin.setOnClickListener(this);

		LinearLayout.LayoutParams param4 = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, BUTTON_HEIGHT);
		layoutLogin.addView(m_buttonLogin, param4);

		m_buttonLogout = LayoutUtil.makeCtrlButton(getContext(), CTRL_ID_LOGOUT, "로그아웃");
		m_buttonLogout.setOnClickListener(this);

		LinearLayout.LayoutParams param5 = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, BUTTON_HEIGHT);
		layoutLogin.addView(m_buttonLogout, param5);

		LinearLayout.LayoutParams paramLogin = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, TITLE_HEIGHT);
		paramLogin.topMargin = PADDING_V * 3;
		layoutFrame.addView(layoutLogin, paramLogin);

		m_viewUserInfo = new UserInfoView(getContext());

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

		addView(layoutFrame, new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, Gravity.TOP | Gravity.CENTER_HORIZONTAL));

		resetUserInfo();
	}

	public void releaseView()
	{
		removeAllViews();

	}

	private void resetUserInfo()
	{
		int nLoginType = SmartChampAPI.getInstance().getLoginType();

		if(nLoginType == SmartChampDefs.LOGIN_TYPE_SISE)
		{
			m_buttonLogin.setVisibility(View.VISIBLE);
			m_buttonLogin.setText("공동인증로그인");
			m_buttonLogout.setVisibility(View.VISIBLE);
		} else if(nLoginType == SmartChampDefs.LOGIN_TYPE_CERT)
		{
			m_buttonLogin.setVisibility(View.GONE);
			m_buttonLogout.setVisibility(View.VISIBLE);
		} else {
			m_buttonLogin.setVisibility(View.VISIBLE);
			m_buttonLogin.setText("로그인");
			m_buttonLogout.setVisibility(View.GONE);
		}

		if(m_viewUserInfo != null)
			m_viewUserInfo.setUserInfo();
	}

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

		if(nId >= CTRL_ID_MENU_START && nId < (CTRL_ID_MENU_START + m_arrMenus.length))
		{
			if(m_viewCurrent != null)
			{
				removeView(m_viewCurrent);
				m_viewCurrent.releaseView();
				m_viewCurrent = null;
			}

			int nMenuIndex = nId - CTRL_ID_MENU_START;

			if(SmartChampAPI.getInstance().getLoginType() < m_arrMenuAuth[nMenuIndex])
			{
				// 로그인 유형이 선택한 메뉴에 맞지 않는 경우
				Toast.makeText(getContext(), "선택한 메뉴 이용을 위해 로그인이 필요합니다.", Toast.LENGTH_SHORT).show();
				showLogin();
				return;
			}

			Class classMenu = m_arrScreen[nMenuIndex];
			if(classMenu != null)
			{
				try {
					Constructor cons = classMenu.getConstructor(new Class[] { Context.class });
					if(cons != null)
					{
						SiseBaseView viewMenu = (SiseBaseView) cons.newInstance(getContext());
						viewMenu.initView(getContext(), m_activity);

						addView(viewMenu);
						m_viewCurrent = viewMenu;
					}
				} catch (NoSuchMethodException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InstantiationException e) {
					e.printStackTrace();
				}
			}
		} else if(nId == CTRL_ID_LOGIN)
		{
			if(m_viewParent != null)
				m_viewParent.showLoginDialog();
		} else if(nId == CTRL_ID_LOGOUT)
		{
			SmartChampAPI.getInstance().logoutUser();
		} else if(nId == CTRL_ID_CHANGESERVER)
		{
			final String strDevMode = SampleUtil.getConfig(getContext(), "dev_mode", SmartChampDefs.SERVER_MODE_DEFAULT);

			AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
			builder.setTitle("접속서버 변경");
			builder.setMessage((strDevMode.equals("1") ? "운영" : "개발") + "서버로 접속을 변경합니다.\n\n앱이 재시작 됩니다.");
			builder.setPositiveButton("예", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();

					SampleUtil.setConfig(getContext(), "dev_mode", strDevMode.equals("1") ? "0" : "1");

					Intent intent = m_activity.getPackageManager().getLaunchIntentForPackage(m_activity.getPackageName());

					Intent restart = Intent.makeRestartActivityTask(intent.getComponent());
					m_activity.startActivity(restart);

					//m_activity.finish();
					Runtime.getRuntime().exit(0);
				}
			});
			builder.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});

			builder.show();
		}
	}

	@Override
	public boolean onBackPressed()
	{
		if(m_viewCurrent != null)
		{
			if(m_viewCurrent.onBackPressed()) return true;

			removeView(m_viewCurrent);
			m_viewCurrent.releaseView();
			m_viewCurrent = null;

			return true;
		}

		return false;
	}

	@Override
	public void onRefreshView()
	{
		if(m_viewCurrent != null)
			m_viewCurrent.onRefreshView();

		resetUserInfo();
	}
}
