package com.cwbuyer.main;

import java.io.File;
import java.io.IOException;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.cwbuyer.format.IDialog;
import com.cwbuyer.lib.AppUtil;
import com.cwbuyer.lib.DBCloud;
import com.cwbuyer.lib.DateUtil;
import com.cwbuyer.lib.PrefKey;
import com.cwbuyer.lib.SysSetup;
import com.cwbuyer.lib.Utilis;
import com.pwbuyer.main.R;

@SuppressLint("InflateParams")
public class Setup extends PreferenceActivity {

  
  @Override
  public void onConfigurationChanged(Configuration config) {
	super.onConfigurationChanged(config);
	
//	setAutoRotationMode();
//	int i = getRequestedOrientation();
	
	switch (getRequestedOrientation()) {
		case ActivityInfo.SCREEN_ORIENTATION_PORTRAIT:
			if (config.orientation == Configuration.ORIENTATION_PORTRAIT) {
//				((RelativeLayout)findViewById(R.id.body)).setBackgroundResource(R.drawable.background);
			}
			break;
		case ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE:
			if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
//				((RelativeLayout)findViewById(R.id.body)).setBackgroundResource(R.drawable.background_land);
			}
			break;
		case ActivityInfo.SCREEN_ORIENTATION_SENSOR:
			if (config.orientation == Configuration.ORIENTATION_LANDSCAPE){
//				((RelativeLayout)findViewById(R.id.body)).setBackgroundResource(R.drawable.background_land);
			}else{
//				((RelativeLayout)findViewById(R.id.body)).setBackgroundResource(R.drawable.background);
			}
		default:
			break;
	}
  }
  
  /** Called when the activity is first created. */
  
  @SuppressWarnings("deprecation")
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    
    //V 1.2 設定屏幕方向
    Utilis.setAutoRotationMode(this);
    
//    getPreferenceManager().setSharedPreferencesName(PrefKey.NAME);
    
//    Utils.setAutoRotationMode(this);
    
//    if (getString(R.string.app_payuser).equalsIgnoreCase("1")) {
      addPreferencesFromResource(R.xml.free_preferences);
//    } else {
//      addPreferencesFromResource(R.xml.free_preferences);
//    }
//    TAG = getString(R.string.mainmenu_menu_setup_name);
//      setTitle(getString(R.string.app_name) + " - Ver " + getString(R.string.app_version) + " - " + TAG);
  }

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

  
  public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen, Preference preference) {
	  if (preference.getKey().equalsIgnoreCase("key_market_suggest")) {
		  try{
		      Intent goToMarket = null;
		      goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse("http://"+Utilis.getIni(this, "USER", "COMPANY",2)));
		      startActivity(goToMarket);
			  
		  }catch(Exception e){
			  e.printStackTrace();
		  }
/*
		  try{
		      Intent goToMarket = null;
		      goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.cwbuyer.main"));
		      startActivity(goToMarket);
		  }catch(Exception e){
			  e.printStackTrace();
		  }
*/		  
	    } 
	  else if(preference.getKey().equalsIgnoreCase("key_rate")){
		  LayoutInflater factory = LayoutInflater.from(this);
			final View msgEntryView = factory.inflate(
					R.layout.dialog_about, null);
			// 到時候直接連網址
			new AlertDialog.Builder(this)
					.setTitle("Message")
					.setView(msgEntryView)
					.setNegativeButton(R.string.str_cancel,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int whichButton) {
								}
							}).create().show();
	  }
	  else if(preference.getKey().equalsIgnoreCase("key_explain")){
		  try{
		      Intent goToMarket = null;
		      goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.cwbuyer.net/3G006_20123/web/index.php"));
		      startActivity(goToMarket);
		  }catch(Exception e){
			  e.printStackTrace();
		  }
	  }else if(preference.getKey().equalsIgnoreCase("key_share_friend")){
		  getnewVersion(this);
	  }else if(preference.getKey().equalsIgnoreCase("key_cwbuyer")){
		  try{
		      Intent goToMarket = null;
		      goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.cwbuyer.net"));
		      startActivity(goToMarket);
		  }catch(Exception e){
			  e.printStackTrace();
		  }
		    
		}else if(preference.getKey().equalsIgnoreCase("language_preference")){// 設定語言
	    	int oriChoice = Utilis.getIntSet(this, "language_preference", 0);
	    	//之後再加入
	    	Utilis.showDialogCancel(Setup.this, Setup.this.getString(R.string.title_lang_pref), oriChoice, this.getResources().getStringArray(R.array.select_lang), new IDialog(){
				public void onDialogFinish(final int nPos, String choice) {

				}
			});
		}else if(preference.getKey().equalsIgnoreCase("key_reg")){
			LayoutInflater factory = LayoutInflater.from(Setup.this);
		    final View v1 = factory.inflate(R.layout.register, null);
		    final EditText edtReg = (EditText) v1.findViewById(R.id.edtReg);
		    edtReg.setText("");
		    String aDay=Utilis.getStringSet(Setup.this, PrefKey.LIMIT_TIME_LAST, "2010/01/01");
	    	if (DateUtil.compareTime(DateUtil.addDate(DateUtil.getCurrentDate(), 14),aDay ) >= 0){
		    		aDay=Utilis.getStringSet(Setup.this, PrefKey.LIMIT_TIME_ZONA, "1234567890123");
		    	
		      new AlertDialog.Builder(Setup.this).setTitle(Setup.this.getString(R.string.sys_msg_regtitle)+aDay).setView(v1).setNeutralButton("OK", new DialogInterface.OnClickListener() {
		    	
		      public void onClick(DialogInterface dialog, int which) {
		        Utilis.setStringSet(Setup.this, PrefKey.LIMIT_TIME_ZONB, edtReg.getText().toString());
		        if (edtReg.getText().toString().length() != 13) {
		          new AlertDialog.Builder(Setup.this).setTitle(Setup.this.getString(R.string.sys_msg_title)).setMessage(Setup.this.getString(R.string.sys_msg_reg_plzinput)).setPositiveButton("OK", new DialogInterface.OnClickListener() {
		            public void onClick(DialogInterface dialog, int which) {
		            	
		            }
		          }).setCancelable(false).show();
		        }else{
		      	  // 判斷 註冊碼是否正確
		      	  if(AppUtil.isRegSucceed(Setup.this,0) == 0){ 
		      		  new AlertDialog.Builder(Setup.this).setTitle(Setup.this.getString(R.string.sys_msg_title)).setMessage(Setup.this.getString(R.string.sys_msg_reg_success)).setPositiveButton("OK", new DialogInterface.OnClickListener() {
		                    public void onClick(DialogInterface dialog, int which) {
		            		    //String aDay[]=Utilis.getMonthDate().split("~");
		            		    //AppUtil.goRegistAt(Setup.this,aDay[1]);
		                    	//註冊起算日從當月一日改為系統的最後期限日起算
		            		    String aDay=Utilis.getStringSet(Setup.this, PrefKey.LIMIT_TIME_LAST, "2010/01/01");
		            		    AppUtil.goRegistAt(Setup.this,aDay);
		                    }
		                  }).setCancelable(false).show();
		      	  }else{
		      		  new AlertDialog.Builder(Setup.this).setTitle(Setup.this.getString(R.string.sys_msg_title)).setMessage(Setup.this.getString(R.string.sys_msg_reg_plzinput)).setPositiveButton("OK", new DialogInterface.OnClickListener() {
		                    public void onClick(DialogInterface dialog, int which) {
		                    }
		                  }).setCancelable(false).show();
		      	  }
		        }
		      }
		    }).setNegativeButton("離開", new DialogInterface.OnClickListener() {
		      public void onClick(DialogInterface dialog, int which) {
		      }
		    }).setPositiveButton("購買", new DialogInterface.OnClickListener() {
			      public void onClick(DialogInterface dialog, int which) {
			    	  if(Utilis.haveInternet(Setup.this)){
			    		  try{
			    		      Intent goToBuy = null;
//			    		      goToBuy = new Intent(Intent.ACTION_VIEW, Uri.parse("http://lib.com.tw/cwbuyer/reg.aspx"));
			    		      goToBuy = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.cwbuyer.net"));			    		      
			    		      Setup.this.startActivity(goToBuy);
			    		  }catch(Exception e){
			    			  e.printStackTrace();
			    		  }
			    	  }else{
			    		  Toast.makeText(Setup.this, "需開啟3G or Wifi無線網路", Toast.LENGTH_SHORT).show();
			    	  }
			      }
			})
		    .show();
	    	} else {Toast.makeText(Setup.this, "有效期限:"+aDay+"無需註冊", Toast.LENGTH_SHORT).show();} 		
		}else if(preference.getKey().equalsIgnoreCase("key_setup")){
	        if (Utilis.getIni(this,"SYS","DEPT",5).equalsIgnoreCase("0")){  //密碼OK 或不用密碼
        		Intent  intent = new Intent();
        		intent.setClass(Setup.this, SysSetup.class);
        		startActivity(intent);
	        }
		}
	 
	  
    return true;
  }
  
  public static void getnewVersion(Context context) {

  	boolean success=false;
	try {
        File dnPath = new File(android.os.Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"CWBuyer/IMPORT/20123");
      if (!dnPath.exists()){
      	dnPath.mkdirs();  //若不存在 則建立之
      }else{
      	File file[] = dnPath.listFiles();
			for (int i=0; i < file.length; i++)
			{
				if (file[i].getName().indexOf("buyer")>=0){
					Utilis.DeleteFile(dnPath+File.separator+file[i].getName());
				}	
			}
      }
      
		final File localFile = new File(dnPath+File.separator+"cwbuyerpos.apk");
		success=DBCloud.ftpDownloadAndSaveFile(context,"210.242.76.219", 21,"CWBUYERPOS_3G000", Utilis.getIni(context, "SYS", "IMPORT",5), "CWBuyerPos.apk", localFile);
		
		if (success==true){
			Intent goToMarket = new Intent(Intent.ACTION_VIEW);  
			goToMarket.setDataAndType(Uri.fromFile(localFile),"application/vnd.android.package-archive");  
			context.startActivity(goToMarket);
		}
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	  
  }

  public  static  String getPackageNameForAPK ( final  String archiveFilePath ,  Context context )  { 
      try  { 
          PackageInfo info = context . getPackageManager (). getPackageArchiveInfo ( archiveFilePath ,  PackageManager . GET_META_DATA ); 
          return info . packageName ; 
      }  catch  ( Exception ex )  { 
          ex . printStackTrace (); 
          return  null ; 
      }

  }  
  
  
}