
package com.tcl.factory.view;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import android.tclwidget.TCLAlertDialog;
import android.view.KeyEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.tcl.customerapi.R;
import com.tcl.factory.bsp.TCL;
import com.tcl.factory.bsp.TV;
import com.tcl.factory.bsp.TVDefine;
import com.tcl.factory.def.DEFS;
import com.tcl.factory.def.KeyMap;
import com.tcl.factory.thirdparty.ThirdParty;
import com.tcl.factory.utils.Debug;
 

public class MainMenu extends ListActivity  
{
	private final String TAG = this.getClass().getName();
	
	public static  String info_list_value[]={
		"","","","","","",""
	};
	public static  String info_lable_list[]={
		"SW NO :","Project Name","Panel Name","SIAP Version","Date:","Dongle Version"
	};
	
	/** Called when the activity is first created. */
	ArrayList<HashMap<String,String>> list=new ArrayList<HashMap<String,String>>() ;
	ArrayList<SubMenu>menuStack =new ArrayList<SubMenu>() ;// Menu stack, mainly used for page switch????
	
	private TextView label=null;
	public static TextView InfoListLabel=null;
	public static TextView InfoListValue=null;
		
	public static LinearLayout mainArea=null;
	public static RelativeLayout infoArea=null;
	
	private Handler handlerUpdateUi = new Handler();

	private String[][]  menuInfos=null;

	public static SubMenu mSubMenu;
	public static SubMenu mSubMenuTmp;
	
	private Context mContext;
	public static MainMenu _Instance = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fac_main);
		findViewId();	
	
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()   
        .detectDiskReads()   
        .detectDiskWrites()   
        .detectNetwork()   // or .detectAll() for all detectable problems   
        .penaltyLog()   
        .build());   
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()   
        .detectLeakedSqlLiteObjects()   
        .detectLeakedClosableObjects()   
        .penaltyLog()   
        .penaltyDeath()   
        .build());
        
        mContext = this.getApplicationContext();
        _Instance = this;
        
		getInstanceOfTV();

		TCL.setInfoDisServiceEnable(DEFS.Enable);

		selectDisplayMenu();
		DEFS.DebugLevel = 4;//TV.readV(TVDefine.NVM, DEFS.EEPROM_ADDR_DebugLevel);
		Debug.v(TAG, "onCreate");
	}

	@Override
	protected void onStart() 
	{
		super.onStart();
		Debug.v(TAG, "onStart");
	}
	@Override
	protected void onResume() 
	{
		// TODO Auto-generated method stub

		super.onResume();
		if(ThirdParty.getHotelBootLogoCheckStatus()==DEFS.HOTEL_BOOT_LOGO_CHECK_STATUS_LOGO)
		{
			ThirdParty.setHotelBootLogoCheckStatus(DEFS.HOTEL_BOOT_LOGO_CHECK_STATUS_NULL);
			UserLogoSelectConfirmDialog();
		}
		updateDetailInfoLayer();
		Debug.v(TAG, "onResume");
	}

	@Override
	protected void onDestroy() 
	{
		if(!TV.readS(TVDefine.DPMode))
			TCL.setInfoDisServiceEnable(DEFS.Disable);
 		super.onDestroy();
 		Debug.v(TAG,"onDestroy");
	}

	// a pthread to update main ui
	private Runnable task = new Runnable() 
	{   
		public void run() 
		{    
			if(menuStack.size()>0)
			{
				Debug.v(TAG,"pthread = update ui");
				mSubMenu.updateMenuInfos();
			    int position=getSelectedItemPosition();
				updateView();
			    setSelection(position);
			}
		}   
	};   

	public void updateListView(int time) {
		handlerUpdateUi.postDelayed(task, time);
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) 
	{
		int position=getSelectedItemPosition();
		int keyCode = event.getKeyCode();	
		int cmd_data=(keyCode&0xff00)>>8;

		Debug.v(TAG , "dispatchKeyEvent : event.getAction() = " + event.getAction() + ", event.getKeyCode() = " + event.getKeyCode());

		if(event.getAction() == KeyEvent.ACTION_DOWN)
		{	
			DEFS.keyCodeRecord=(short) keyCode;//record the receive kdycode for UART query
			Debug.v(TAG,"keycode... = " + DEFS.keyCodeRecord);
			Debug.v(TAG,"event.getScanCode()... = " + event.getScanCode());
			Debug.v(TAG,"cmd_data... = " + cmd_data);
			
			if(cmd_data!=0 && keyCode != 4081 && keyCode != 4026) { // 4081ҲΪ�ؿ���
//				Debug.v(TAG, "KEYCODE_FACIR");
//				IRManager.parser(keyCode);
				handlerUpdateUi.postDelayed(task, 1000);
				return true;
			}
			Debug.v(TAG,"event.getScanCode()... = " + event.getScanCode());
			if(event.getScanCode() == 249 || keyCode == 4081) {  //BACK / �ؿ�
				keyCode = KeyMap.KEYCODE_BACK;
			}

			if(menuStack.size()>0)// Prevent listsize is null
			{			    
				switch(keyCode)
				{
				case KeyMap.KEYCODE_SUB_MENU:
				case KeyMap.KEYCODE_SUB_MENU_FOR_OVERSEA:
				{
					enterPrevMenu();
					return true;
				}
				case KeyMap.KEYCODE_BACK:
				{
					finish();
					return true;
				}
				case KeyMap.KEYCODE_ENTER:
				case KeyMap.KEYCODE_DPAD_CENTER:
				{
					mSubMenu.setMenuPosition(position);
					mSubMenuTmp=mSubMenu;
//					mSubMenu.nextMenu(position);	
					mSubMenu.enterSubMenu(position);
					if(!mSubMenu.equals(mSubMenuTmp))
				 	  enterNextMenu(mSubMenu);
				}
				break;
				case KeyMap.KEYCODE_DPAD_LEFT:
				case KeyMap.KEYCODE_DPAD_RIGHT:
					mSubMenu.KeyEvent(keyCode,position);
					/*
					if(ThirdParty.IsEUArea())
					{
						if(mSubMenu.getClass().getName().toUpperCase().contains("PMODEMENU"))
						{
							if((mSubMenu.getMenuInfos())[position][0].toUpperCase().contains("SHOP"))
							{
								finish();
							}
						}
					}*/
					handlerUpdateUi.postDelayed(task, 100);
					break;
				case KeyMap.KEYCODE_DPAD_DOWN: 
				{
					while(true)
					{   
						if(position >= mSubMenu.getMenuInfosLength()-1)
						{
							//setSelection(0) ;
							//break;
							mSubMenu.KeyEvent(keyCode,position);
							position = 0;
						}
						else
						{
							position++;
						}
						int i=mSubMenu.getNextDisplayItem(position);
						
						Debug.v(TAG,"key down getNextDisplayItem = " + i);
						
						if(i==0)
						{
							Debug.v(TAG, "position="+position);
						}
						else
						{
							setSelection(position) ;
							return true;
						}
					}
				}
				case KeyMap.KEYCODE_DPAD_UP: 
				{
					while(true)
					{   
						if(position<=0)
						{
							//setSelection(mSubMenu.getMenuInfosLength()-1) ;
							//return true;
							mSubMenu.KeyEvent(keyCode,position);
							position = mSubMenu.getMenuInfosLength()-1;
						}
						else
						{
							position--;
						}
						int i=mSubMenu.getNextDisplayItem(position);
						Debug.v(TAG,"key up getNextDisplayItem = " + i);
						if(i==0)
						{
						}
						else
						{
							setSelection(position) ;
							return true;
						}
					}
				}
				case KeyMap.KEYCODE_CHDN:
					TV.writeV(TVDefine.ChannelDown);
 					break;
				
				case KeyMap.KEYCODE_CHUP:
					TV.writeV(TVDefine.ChannelUp);
					break;
				case KeyMap.KEYCODE_0:
				case KeyMap.KEYCODE_1:
				case KeyMap.KEYCODE_2:
				case KeyMap.KEYCODE_3:
				case KeyMap.KEYCODE_4:
				case KeyMap.KEYCODE_5:
				case KeyMap.KEYCODE_6:
				case KeyMap.KEYCODE_7:
				case KeyMap.KEYCODE_8:
				case KeyMap.KEYCODE_9:
					if(mSubMenu.numKeyEvent(keyCode,position)) {
						break;
					}
					int i= keyCode - 7;

					if((TV.readS(TVDefine.PMode)==DEFS.Disable)&&(i==1)) {//warm up 	
						return true;
					}
					
					setSelection(i);
					break;
				case KeyMap.KEYCODE_RETURN: //return Key
					finish();
					return true;
					
				case KeyMap.KEYCODE_MUTE://audio mute 
					if(TV.readS(TVDefine.AudioMute))
					{
						TV.writeS(TVDefine.AudioMute, DEFS.Disable);
 					}
					else
					{
						TV.writeS(TVDefine.AudioMute, DEFS.Enable);
					}
					return true;	
				case KeyMap.KEYCODE_SOURCE:				
					return true;
					
				}////switch end
			}////if end
			else 
			{
				if(TV.readS(TVDefine.DMode)==DEFS.Enable)
				{
					menuStack.add(new DModeMainMenu(MainMenu.this));
				}
				
				else if(TV.readS(TVDefine.PMode)==DEFS.Enable)
				{
					menuStack.add(new PModeMenu());
				}
				return true;
			}
		}
		return super.dispatchKeyEvent(event);
	}

	private void buildNewMenu()
	{   
		menuInfos = mSubMenu.getMenuInfos();
		label.setText(mSubMenu.getMenuLable());
		list.clear();
		for(int i=0;i< menuInfos.length;i++)
		{
			HashMap<String,String> map=new  HashMap<String,String>();
			map.put("itemname", menuInfos[i][0]);
			map.put("Status", menuInfos[i][1]);
			list.add(map);
		}
		SimpleAdapter listAdapter=new SimpleAdapter(this,list,R.layout.fac_item_lay, new String[]{"itemname","Status"},new int[]{R.id.label,R.id.value} );
		setListAdapter(listAdapter); 
	}

	void updateView()
	{   
		for(int i=0;i<menuInfos.length;i++)
		{
			list.get(i).put("Status", menuInfos[i][1]);
			list.get(i).put("itemname", menuInfos[i][0]);
		}
		
		SimpleAdapter listAdapter=new SimpleAdapter(this,list,R.layout.fac_item_lay,new String[]{"itemname","Status"},new int[]{R.id.label,R.id.value} );
		setListAdapter(listAdapter); 
	}
	public void enterNextMenu(SubMenu mSubMenu)
	{  
		menuStack.add(mSubMenu);//���µ�MENU ���� ��ջ
		buildNewMenu();//��UI
	}

	public void enterPrevMenu()//�ص�ǰһ��UI
	{

		int num=menuStack.size();
		if(num>1){
			mSubMenu=menuStack.get(num-2);//��ȡ ����ڶ�???? ����
			menuStack.remove(num-1);//�Ƴ���ջ
			mSubMenu.updateMenuInfos();
			buildNewMenu();//��UI
			int position=mSubMenu.getMenuPosition();//��ȡ����	
			setSelection(position);//���ý���
		}
		else 
		{			
			finish();
		}
	}


	//update the detail info about the TV
	public static  void updateDetailInfoLayer()
	{ 
		int indexProjectID = TV.readV(TVDefine.ProjectID);
		StringBuffer infoStr=new StringBuffer(""); 
		StringBuffer infoStrValue=new StringBuffer(""); 
		
		info_list_value[0]=DEFS.projectInfo.getSoftwareVer();//Sw ver
		info_list_value[1]=DEFS.projectInfo.getProjectName(indexProjectID);
		info_list_value[2]=DEFS.projectInfo.getPannelName();
		info_list_value[3]=DEFS.projectInfo.getSiacp();//uart 4.1
		info_list_value[4]=DEFS.projectInfo.getDate();//build data
		info_list_value[5]=DEFS.projectInfo.read_RC71S_DongleVesion();
		for(int i = 0; i < info_lable_list.length; i++)
		{
			infoStr=infoStr.append(info_lable_list[i]);
			infoStr.append("\n");
			infoStrValue=infoStrValue.append(info_list_value[i]);	
			infoStrValue.append("\n");
		}

		InfoListLabel.setText(infoStr);
		InfoListValue.setText(infoStrValue);
	}

	public 	void selectDisplayMenu()
	{
		Intent intent = getIntent();        
		int value = intent.getIntExtra("select", 0);
		int osdShow= intent.getIntExtra("osdlabel", 0);

		Debug.v(TAG, "value = "+value);
		Debug.v(TAG, "osdShow = "+osdShow);

		menuStack.clear();
		switch(value){
		case DEFS.D_MODE:
			menuStack.add(new DModeMainMenu(MainMenu.this)); 
			break;//DmodeMainMenu display
		case DEFS.P_MODE:
			menuStack.add(new PModeMenu()); 
			break;//PmodeMainMenu display7
		case DEFS.W_MODE:
			menuStack.add(new PModeMenu());
			TV.writeS(TVDefine.WarmUP, DEFS.Enable);
			break;//begin warm up
		case DEFS.S_MODE:
			menuStack.add(new DModeServerMenu(MainMenu.this));
			break;//server menu on
		case DEFS.HOTEL_MODE:
			if(ThirdParty.getHotelFlag() == DEFS.COMMON_ON){
				menuStack.add(new HotelMainMenu(MainMenu.this));
			}
			break;//hotel menu on
		case DEFS.AFTER_SALE_MODE:
			menuStack.add(new DModeAfterSaleMenu(MainMenu.this)); 
			infoArea.setVisibility(View.INVISIBLE);
			break;				
		case DEFS.RECORD_MODE:
			menuStack.add(new DModeRecordMenu(MainMenu.this));
			infoArea.setVisibility(View.INVISIBLE);	
			break;
		default:
			menuStack.add(new DModeMainMenu(MainMenu.this));//default
			break;
		}
		mSubMenu=menuStack.get(0);
		buildNewMenu();
		MainMenu.mainArea.setVisibility(View.VISIBLE);
	}
	
	private void findViewId()
	{
		label=(TextView)findViewById(R.id.path);//path label

		InfoListLabel=(TextView)findViewById(R.id.SW_NO);
		InfoListValue=(TextView)findViewById(R.id.Sw_No_Value);
		mainArea=(LinearLayout)findViewById(R.id.mainDisplayArea);// main menu
		mainArea.setVisibility(View.VISIBLE);
		infoArea = (RelativeLayout)findViewById(R.id.sys_info);		//info menu
	}
	
	private void getInstanceOfTV(){
		TCL.implemetThirdPartyIsntance(this);
	}

	private void UserLogoSelectConfirmDialog(){
		Debug.v(TAG, "LogoSelectConfirmDialog");
		AlertDialog.Builder builder = new AlertDialog.Builder(MainMenu.this);
		builder.setTitle("Do you want to set up as the new boot logo?").setIcon(TCLAlertDialog.INFO_IMAGE);
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
			}
		});
		builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
			}
		});
		builder.show();
	}
	
	public void MainMenuSetSelection(int position)
	{
		setSelection(position) ;
	}
}