package com.cwbuyer.lib;

import android.annotation.SuppressLint;
import android.app.Activity; 
import android.app.PendingIntent; 
import android.content.Context;
import android.content.Intent; 
import android.os.Bundle; 
import android.telephony.SmsManager; 
import android.view.LayoutInflater;
import android.view.View; 
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.pwbuyer.main.R;


@SuppressLint("InflateParams")
@SuppressWarnings("unused")
public class Qsms_one extends Activity  
{ 
  /*宣告變數一個Button與兩個EditText*/

  private List<HashMap<String, Object>> albun_list = null;    
  private Button mButton1; 
  private TextView mText1; 
  private EditText mEditText2;
  ListView lv = null;
  private MyAdapter adapter;
  
  //for email
private String strEmailSubject; 
  private String[] strEmailCc;
  private String strEmailBody ; 
   
  /** Called when the activity is first created. */ 
@SuppressWarnings("unchecked")
@Override 
  public void onCreate(Bundle savedInstanceState) 
  { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.qsms_one);
    
    
    /*透過findViewById建構子來建構EditText2與Button物件*/ 
    mText1 = (TextView) findViewById(R.id.myText1);
        //簡訊內文
    mEditText2 = (EditText) findViewById(R.id.myEditText2); 
    mButton1 = (Button) findViewById(R.id.myButton1);
    lv = (ListView) this.findViewById(R.id.listView17);
    

	 Bundle bundle = this.getIntent().getExtras();
	  String fromW=bundle.getString("Qsms");
	  String[] array = fromW.split(",");
		String myFilePath=array[0];
		final String app=array[1];
		
		
		FileInputStream istream = null;
		ObjectInputStream br = null;

		try {
			istream = new FileInputStream(myFilePath);
			br = new ObjectInputStream(istream);
			
			albun_list =(List<HashMap<String, Object>>)br.readObject();
			br.close();
			istream.close();
				if (app.equalsIgnoreCase("sms")) {
					mText1.setText(getResources().getText(R.string.str_sms_tot).toString()+albun_list.size()+getResources().getText(R.string.str_sms_sending).toString());

				} else if (app.equalsIgnoreCase("email")) {
					mText1.setText(getResources().getText(R.string.str_sms_tot).toString()+albun_list.size()+getResources().getText(R.string.str_mail_sending).toString());
					mButton1.setText(getResources().getText(R.string.str_sms_buttonx).toString());					
				}
				adapter = new MyAdapter(this, albun_list, R.layout.mainlist_1,
                    new String[] { "eno" ,"ename" ,"emobil" ,"eemail" ,"ebars" ,"epics" }, new int[] {
                            R.id.item_tv,R.id.item_tv1,R.id.item_tv2,R.id.item_tv3,R.id.item_tv4,R.id.item_tv5});
					lv.setAdapter(adapter);
        	
		}
		catch (Exception e) {
			
		}	
    
    /*設定onClickListener 讓使用者點選Button時做出反應*/
    mButton1.setOnClickListener(new Button.OnClickListener() 
    { 
      @Override 
      public void onClick(View v) 
      { 

        /*由EditText2取得簡訊/郵件 文字內容*/
        String strMessage = mEditText2.getText().toString(); 
        /*建構一取得default instance的 SmsManager物件 */
        SmsManager smsManager = SmsManager.getDefault();
//        if ((app.equalsIgnoreCase("sms") && iswithin70(strMessage)==true) || app.equalsIgnoreCase("email")) {
       if (strMessage.length()>0 ) {
        if (app.equalsIgnoreCase("sms") ) {
        	if (iswithin70(strMessage)==true) { 	
        		for (int dd=0;dd<albun_list.size();dd++){
        			HashMap<String, Object> map = albun_list.get(dd);
        			String strDestAddress=(String) map.get("emobil");
//        			mText1.setText("共有 "+albun_list.size()+" 筆之第 "+(dd+1)+"筆 "+strDestAddress +"正在傳送!");
        			// TODO Auto-generated method stub 
        			/*檢查收件人電話格式與簡訊字數是否超過70字元*/
        			if(isPhoneNumberValid(strDestAddress)==true )	{
        				try 
        				{ 
        					/*兩個條件都檢查通過的情況下,發送簡訊
        					 * 先建構一PendingIntent物件並使用getBroadcast()方法進行Broadcast
        					 * 將PendingIntent,電話,簡訊文字等參數傳入sendTextMessage()方法發送簡訊*/
        					PendingIntent mPI = PendingIntent.getBroadcast(Qsms_one.this, 0, new Intent(), 0); 
        					smsManager.sendTextMessage(strDestAddress, null, strMessage, mPI, null); 
        				} 
        				catch(Exception e) 
        				{ 
        					e.printStackTrace(); 
        				} 
        				Toast.makeText(Qsms_one.this,strDestAddress +getResources().getText(R.string.str_sms_sended).toString() ,Toast.LENGTH_SHORT).show();
        		
        			}
        				/*電話格式與簡訊文字不符合條件時,使用Toast告知使用者檢查*/
        			else { /*電話格式不符*/
       					Toast.makeText(Qsms_one.this,getResources().getText(R.string.str_wrong_tel_format).toString() ,Toast.LENGTH_SHORT).show();
        					}
               	 }
        			mText1.setText(getResources().getText(R.string.str_sms_sended).toString());
        				mButton1.setText(getResources().getText(R.string.str_sms_tot).toString()+albun_list.size()+getResources().getText(R.string.str_sms_sended).toString());
        		} else {
        				Toast.makeText(Qsms_one.this,getResources().getText(R.string.str_wrong_sms_tolong).toString(),Toast.LENGTH_SHORT).show();
        				}
        } else { //發郵件
        	
        		String strDestAddress="";
        		int tott=0;
    		for (int dd=0;dd<albun_list.size();dd++){
    			HashMap<String, Object> map = albun_list.get(dd);

    			// TODO Auto-generated method stub
    		   if (isEmail((String) map.get("eemail"))) {
    			   if (strDestAddress.length()<1){
    				   strDestAddress=(String) map.get("eemail");
    			   } else {
    				   strDestAddress=strDestAddress+","+(String) map.get("eemail");
    			   }
    			   tott++;
    		   }
    		}
    				try 
    				{
    					
    					Intent mEmailIntent = new Intent(android.content.Intent.ACTION_SEND);  
    			        mEmailIntent.setType("message/rfc822");

    			        
    			        String[] strEmailReciver = new String[]{strDestAddress};
    			        strEmailCc = new String[]{"purchman123@gmail.com"};
    			        strEmailSubject = mText1.getText().toString();
    			        strEmailBody = mEditText2.getText().toString();
    			        
    			        
//@#@                        Uri U=Uri.parse("file:///sdcard/cwbuyer.sdb");
                        
    			        mEmailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, strEmailReciver); 
    			        mEmailIntent.putExtra(android.content.Intent.EXTRA_CC, strEmailCc);
    			        mEmailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "SUBJECT");
    			        mEmailIntent.putExtra(android.content.Intent.EXTRA_TEXT, strEmailBody);
    			        
//@#@    			        mEmailIntent.putExtra(android.content.Intent.EXTRA_STREAM, U);

    			        startActivity(Intent.createChooser(mEmailIntent, "謹收"));     				


    				}
    				catch(Exception e) 
    				{ 
    					e.printStackTrace(); 
    				} 
           	    
    				mText1.setText(getResources().getText(R.string.str_sms_sended).toString());
    				mButton1.setText(getResources().getText(R.string.str_sms_tot).toString()+tott+getResources().getText(R.string.str_sms_sended).toString());
    				
       } 
      }
     }
    }); 
     
  } //主程式結束


/*檢查字串是否為電子郵件的方法,並回傳true or false的判斷值*/
public static boolean isEmail(String strEmail) 
{ 
  String strPattern = "^[a-zA-Z][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$"; 
  Pattern p = Pattern.compile(strPattern); 
  Matcher m = p.matcher(strEmail); 
  return m.matches(); 
} 

  /*檢查字串是否為電話號碼的方法,並回傳true or false的判斷值*/
  public static boolean isPhoneNumberValid(String phoneNumber)
  {
     boolean isValid = false;
     /* 可接受的電話格式有:
      * ^\\(? : 可以使用 "(" 作為開頭
      * (\\d{3}): 緊接著三個數字
      * \\)? : 可以使用")"接續
      * [- ]? : 在上述格式後可以使用具選擇性的 "-".
      * (\\d{3}) : 再緊接著三個數字
      * [- ]? : 可以使用具選擇性的 "-" 接續.
      * (\\d{4})$: 以四個數字結束.
      * 可以比對下列數字格式:
      * (123)456-7890, 123-456-7890, 1234567890, (123)-456-7890  
     */
     String expression = "^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$";
     /* 可接受的電話格式有:
      * ^\\(? : 可以使用 "(" 作為開頭
      * (\\d{2}): 緊接著兩個數字
      * \\)? : 可以使用")"接續
      * [- ]? : 在上述格式後可以使用具選擇性的 "-".
      * (\\d{4}) : 再緊接著四個數字
      * [- ]? : 可以使用具選擇性的 "-" 接續.
      * (\\d{4})$: 以四個數字結束.
      * 可以比對下列數字格式:
      * (123)456-7890, 123-456-7890, 1234567890, (123)-456-7890  
     */
     String expression2 ="^\\(?(\\d{2})\\)?[- ]?(\\d{4})[- ]?(\\d{4})$";
     CharSequence inputStr = phoneNumber;
     /*建立Pattern*/
     Pattern pattern = Pattern.compile(expression);
     /*將Pattern 以參數傳入Matcher作Regular expression*/ 
     Matcher matcher = pattern.matcher(inputStr);
     /*建立Pattern2*/
     Pattern pattern2 =Pattern.compile(expression2);
     /*將Pattern2 以參數傳入Matcher2作Regular expression*/ 
     Matcher matcher2= pattern2.matcher(inputStr);
     if(matcher.matches()||matcher2.matches())
     {
     isValid = true;
     }
     return isValid; 
   }
  public static boolean iswithin70(String text)
  {
    if (text.length()<= 70)
      return true;
    else
      return false;
  }
  
  
  public static class MyAdapter extends BaseAdapter {
      private Context context = null;
      private LayoutInflater inflater = null;
      private List<HashMap<String, Object>> list = null;
      private String keyString[] = null;
      private String itemString = null; // 记录每个item中textview的值
      private int idValue[] = null;// id值

      public MyAdapter(Context context, List<HashMap<String, Object>> list,
              int resource, String[] from, int[] to) {
          this.context = context;
          this.list = list;
          keyString = new String[from.length];
          idValue = new int[to.length];
          System.arraycopy(from, 0, keyString, 0, from.length);
          System.arraycopy(to, 0, idValue, 0, to.length);
          inflater = LayoutInflater.from(context);
          
      }

      @Override
      public int getCount() {
          return list.size();
      }

      @Override
      public Object getItem(int arg0) {
          return list.get(arg0);
      }

      @Override
      public long getItemId(int arg0) {
          return 0;
      }

      @Override
      public View getView(int position, View view, ViewGroup arg2) {
          ViewHolder holder = null;
          if (holder == null) {
              holder = new ViewHolder();
              if (view == null) {
                  view = inflater.inflate(R.layout.mainlist_1, null);
              }
              holder.tv = (TextView) view.findViewById(R.id.item_tv);
              holder.tv1 = (TextView) view.findViewById(R.id.item_tv1);
              holder.tv2 = (TextView) view.findViewById(R.id.item_tv2);
              holder.tv3 = (TextView) view.findViewById(R.id.item_tv3);
              holder.tv4 = (TextView) view.findViewById(R.id.item_tv4);              
              holder.tv5 = (TextView) view.findViewById(R.id.item_tv5);              
              view.setTag(holder);
          } else {
              holder = (ViewHolder) view.getTag();
          }
          HashMap<String, Object> map = list.get(position);
          if (map != null) {
              itemString = (String) map.get(keyString[0]);
              holder.tv.setText(itemString);

              itemString = (String) map.get(keyString[1]);
              holder.tv1.setText(itemString);
              
              itemString = (String) map.get(keyString[2]);
              holder.tv2.setText(itemString);
              
              itemString = (String) map.get(keyString[3]);
              holder.tv3.setText(itemString);

              itemString = (String) map.get(keyString[4]);
              holder.tv4.setText(itemString);
              
              itemString = (String) map.get(keyString[5]);
              holder.tv5.setText(itemString);
              
          }

          return view;
      }
       
      private class ViewHolder {
          public TextView tv = null;
          public TextView tv1 = null;
          public TextView tv2 = null;
          public TextView tv3 = null;
          public TextView tv4 = null;
          public TextView tv5 = null;
      } 
  }

} 
