package astrology.findyourfate.com;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale; 
import org.json.JSONException; 

import android.content.Context;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Fragment;
import android.app.TimePickerDialog; 
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TimePicker;
import com.paypal.android.sdk.payments.PayPalPayment;
import com.paypal.android.sdk.payments.PayPalService;
import com.paypal.android.sdk.payments.PaymentActivity;
import com.paypal.android.sdk.payments.PaymentConfirmation;


public class namechange extends Fragment {
	
		public namechange(){}
	  EditText mEdit;
	  EditText timer;
	  RadioButton male;
	  String am_pm="";
	  private static final String CONFIG_ENVIRONMENT = PaymentActivity.ENVIRONMENT_NO_NETWORK;
	    
	     private static final String CONFIG_CLIENT_ID = "GB7QEWLT4JRQ6";
	    private static final String CONFIG_RECEIVER_EMAIL = "stanley@findyourfate.com"; 
	
	  EditText fullname,city,state,date,time,other,email;
	Spinner cospin,country;
	 WebView webView;
 Button btn;
 RadioGroup pay,sex;
	 public View onCreateView(LayoutInflater inflater, ViewGroup container,
	            Bundle savedInstanceState) {
		 StrictMode.setThreadPolicy(
				 new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
	        View rootView = inflater.inflate(R.layout.namechange_layout, container, false);
	        
	         
		    
	        webView = (WebView)rootView.findViewById(R.id.myview); 
	        email=(EditText)rootView.findViewById(R.id.email);
	        fullname=(EditText)rootView.findViewById(R.id.fullname);
		     city=(EditText)rootView.findViewById(R.id.city);
		     state=(EditText)rootView.findViewById(R.id.state);
		     date=(EditText)rootView.findViewById(R.id.dateofbirth);
		     time=(EditText)rootView.findViewById(R.id.timeofbirth);
		     other=(EditText)rootView.findViewById(R.id.other);
		     btn=(Button)rootView.findViewById(R.id.button1);
			 country=(Spinner)rootView.findViewById(R.id.countr);       
		     pay=(RadioGroup)rootView.findViewById(R.id.payable);
		     sex=(RadioGroup)rootView.findViewById(R.id.sex);
		     male=(RadioButton)rootView.findViewById(R.id.m);
		     final AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
		     
		      
		        btn.setOnClickListener(new View.OnClickListener() {
		            @Override
		            public void onClick(View v) {
		            	
		            	  String user = email.getText().toString();
		            	  String fname=fullname.getText().toString();
		            	  String cit=city.getText().toString();
		            	  String stat=state.getText().toString();
		            	  String dat=date.getText().toString();
		            	  String tim=time.getText().toString();
		            	  String otherdet=other.getText().toString();
		            	  String count=country.getSelectedItem().toString();
		            	  int value = sex.getCheckedRadioButtonId();
		            	  
		                  String gen;
		                  //checking the id of the selected radio
		                  if(value == male.getId())
		                  {
		                      gen="Male";
		                  }
		                  else
		                  {
		                    gen="Female";
		                  }
		               	String format= "Full name :" +fname +"<br />"
			                +"Gender : " +gen + "<br/>"
			            	+"City :" +cit + "<br />"
			            	+"State : " +stat + "<br/>"
			            	+"Country : " +count + "<br/>"
			            	+"E-mail address : " +user+ "<br/>"
			            	+"Date of birth: " +dat + "<br/>"
			            	+"Time of birth : " +tim + "<br/>"
			            	+"Other details : " +otherdet+ "<br/>"
			            	 +"Details : PayPal - USD 10  "+ "<br/>";
			            
			            	 if(fullname.getText().toString().length() == 0 )
			            	{
			            		 alt_bld.setTitle("Alert Message");
			            		 alt_bld.setMessage("Please enter your first name")
			            		 .setCancelable(false)
			            					 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
			            					 public void onClick(DialogInterface dialog, int id) {
			            						 fullname.requestFocus(); 
			            					 }
			            					 });
			            		 AlertDialog alert = alt_bld.create();
			            		 alert.setTitle("Alert Message");
			            		 alert.setIcon(R.drawable.alert);
			            		 alert.show();
			            		 fullname.setFocusable(true);
			            	}	
			            	else if(city.getText().toString().length() == 0 )
			            	{
			            		 alt_bld.setTitle("Alert Message");
			            		 alt_bld.setMessage("Please enter your city name")
			            		 .setCancelable(false)
			            					 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
			            					 public void onClick(DialogInterface dialog, int id) {
			            						 city.requestFocus(); 
			            					 }
			            					 });
			            		 AlertDialog alert = alt_bld.create();
			            		 alert.setTitle("Alert Message");
			            		 alert.setIcon(R.drawable.alert);
			            		 alert.show();
			            		 city.setFocusable(true);
			            	}	
			            	else if(state.getText().toString().length() == 0 )
			            	{
			            		 alt_bld.setTitle("Alert Message");
			            		 alt_bld.setMessage("Please enter your state name")
			            		 .setCancelable(false)
			            					 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
			            					 public void onClick(DialogInterface dialog, int id) {
			            						 state.requestFocus(); 
			            					 }
			            					 });
			            		 AlertDialog alert = alt_bld.create();
			            		 alert.setTitle("Alert Message");
			            		 alert.setIcon(R.drawable.alert);
			            		 alert.show();
			            		 state.setFocusable(true);
			            	}	
			            	else if(date.getText().toString().length() == 0 )
			            	{
			            		 alt_bld.setTitle("Alert Message");
			            		 alt_bld.setMessage("Please enter your date of birth")
			            		 .setCancelable(false)
			            					 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
			            					 public void onClick(DialogInterface dialog, int id) {
			            						 date.requestFocus(); 
			            					 }
			            					 });
			            		 AlertDialog alert = alt_bld.create();
			            		 alert.setTitle("Alert Message");
			            		 alert.setIcon(R.drawable.alert);
			            		 alert.show();
			            		 date.setFocusable(true);
			            	}	
			            	else if(time.getText().toString().length() == 0 )
			            	{
			            		 alt_bld.setTitle("Alert Message");
			            		 alt_bld.setMessage("Please enter your time of birth")
			            		 .setCancelable(false)
			            					 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
			            					 public void onClick(DialogInterface dialog, int id) {
			            						 time.requestFocus(); 
			            					 }
			            					 });
			            		 AlertDialog alert = alt_bld.create();
			            		 alert.setTitle("Alert Message");
			            		 alert.setIcon(R.drawable.alert);
			            		 alert.show();
			            		 time.setFocusable(true);
			            	}	
	        
			            	else if(country.getSelectedItem().toString().equals("--Select--"))
			            	{
			            		 alt_bld.setTitle("Alert Message");
			            		 alt_bld.setMessage("Please select your country")
			            		 .setCancelable(false)
			            					 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
			            					 public void onClick(DialogInterface dialog, int id) {
			            						 country.requestFocus(); 
			            					 }
			            					 });
			            		 AlertDialog alert = alt_bld.create();
			            		 alert.setTitle("Alert Message");
			            		 alert.setIcon(R.drawable.alert);
			            		 alert.show();
			            		 country.setFocusable(true);
			            	}	
			            	else if (! email.getText().toString().matches("[a-zA-Z0-9._-]+@[a-z]+\\.[a-z]+"))
			                {
			            		 alt_bld.setTitle("Alert Message");
			            		 alt_bld.setMessage("Please enter valid email address")
			            		 .setCancelable(false)
			            					 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
			            					 public void onClick(DialogInterface dialog, int id) {
			            						email.requestFocus(); 
			            					 }
			            					 });
			            		 AlertDialog alert = alt_bld.create();
			            		 alert.setTitle("Alert Message");
			            		 alert.setIcon(R.drawable.alert);
			            		 alert.show();
			            		email.setFocusable(true);
			                }
	        
			            	else if( !(fullname.getText().toString().length() == 0) || !(city.getText().toString().length() == 0)||!(state.getText().toString().length() == 0) || !country.getSelectedItem().toString().equals("--Select--") || !(date.getText().toString().length() == 0)||!(time.getText().toString().length() == 0) )
			            	{
			            		
			            		
			            		     
			            		 try {   
			                        	   
			            			 GMailSender sender = new GMailSender(user,format,"Names Correction - Confirmation Details  - findyourfate.com apps" );
					                  
			            		//	 sender.sendMail("Names Correction - Confirmation Details  - findyourfate.com apps",  format,                              user,                                   "analyst@findyourfate.com");  
  	                     } catch (Exception e) {   
			                         Log.e("SendMail", e.getMessage(), e);   
			                     } 
			            		
			            		 Intent intent = new Intent(getActivity(), PayPalService.class);
		            	         
			            	        intent.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, CONFIG_ENVIRONMENT);
			            	        intent.putExtra(PaymentActivity.EXTRA_CLIENT_ID, CONFIG_CLIENT_ID);
			            	        intent.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL, CONFIG_RECEIVER_EMAIL);
			            	         
			            	        startService(intent);
			            	      
			            		 PayPalPayment thingToBuy = new PayPalPayment(new BigDecimal("10.00"), "USD", "Names Correction -  Payment Confirmation Details - findyourfate.com Apps");
			            		  
			            	        
			            		  Intent intent1 = new Intent(getActivity(), PaymentActivity.class);  
			                       
			            		  intent1.putExtra(PaymentActivity.EXTRA_PAYPAL_ENVIRONMENT, CONFIG_ENVIRONMENT);
			            	        intent1.putExtra(PaymentActivity.EXTRA_CLIENT_ID, CONFIG_CLIENT_ID);
			            	        intent1.putExtra(PaymentActivity.EXTRA_RECEIVER_EMAIL, CONFIG_RECEIVER_EMAIL);
			            	         
			            	        // It's important to repeat the clientId here so that the SDK has it if Android restarts your 
			            	        // app midway through the payment UI flow.
			            	        intent1.putExtra(PaymentActivity.EXTRA_CLIENT_ID, "credential-from-developer.paypal.com");
			            	        intent1.putExtra(PaymentActivity.EXTRA_PAYER_ID, "your-customer-id-in-your-system");
			            	        intent1.putExtra(PaymentActivity.EXTRA_PAYMENT, thingToBuy);
			            	       
			            	        startActivityForResult(intent1, 0);
		             
			            	}
			            		}

					private void startService(Intent intent) {
						// TODO Auto-generated method stub
						
					}
		                    });
	        
		        cospin=(Spinner)rootView.findViewById(R.id.countr);
	        
	        mEdit=(EditText)rootView.findViewById(R.id.dateofbirth); 
	        timer=(EditText)rootView.findViewById(R.id.timeofbirth); 
	        
	        final Calendar myCalendar = Calendar.getInstance();

	        final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

	            @Override
	            public void onDateSet(DatePicker view, int year, int monthOfYear,
	                    int dayOfMonth) {
	                // TODO Auto-generated method stub
	                myCalendar.set(Calendar.YEAR, year);
	                myCalendar.set(Calendar.MONTH, monthOfYear);
	                myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
	                updateLabel();
	            }
	            private void updateLabel() {

		            String myFormat = "dd/MM/yyyy"; //In which you need put here
		            SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

		            mEdit.setText(sdf.format(myCalendar.getTime()));
		          
		            }
		       

	        };

	         mEdit.setOnClickListener(new OnClickListener() {

	                @Override
	                public void onClick(View v) {
	                    // TODO Auto-generated method stub
	                    new DatePickerDialog(getActivity(), date, myCalendar
	                            .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
	                            myCalendar.get(Calendar.DAY_OF_MONTH)).show();
	                }
	            });
	        timer.setOnClickListener(new OnClickListener() {

	             @Override
	             public void onClick(View v) {
	                 // TODO Auto-generated method stub
	                 Calendar mcurrentTime = Calendar.getInstance();
	                 int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
	                 int minute = mcurrentTime.get(Calendar.MINUTE);
	                 TimePickerDialog mTimePicker;
	                 mTimePicker = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() {
	                     @Override
	                     public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
	                    	 if(selectedHour < 12) {
	                             am_pm = "AM";
	                         } else {
	                             am_pm = "PM";
	                         }
	                         timer.setText( "" + selectedHour + ":" + selectedMinute+ "" + am_pm);
	               
	                     }
	                 }, hour, minute, true);
	                 mTimePicker.setTitle("Select Time");
	                 mTimePicker.show();

	             }
	         });

 String[] items = getResources().getStringArray(R.array.country_array);
	      
	        
	        final ArrayList<String> list = new ArrayList<String>();
	         for (int i = 0; i < items.length; ++i) {
	           list.add(items[i]);
	         }
	        
	          
	         final StableArrayAdapter adapter = new StableArrayAdapter(getActivity(),android.R.layout.simple_spinner_dropdown_item, list);
	         
	         cospin.setAdapter(adapter);
	        
	        
	        return rootView;
	 }
	
	class StableArrayAdapter extends ArrayAdapter<String> {

		    HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();

		    public StableArrayAdapter(Context context, int textViewResourceId,
		        List<String> objects) {
		      super(context, textViewResourceId, objects);
		      for (int i = 0; i < objects.size(); ++i) {
		        mIdMap.put(objects.get(i), i);
		      }
		    }

		    @Override
		    public long getItemId(int position) {
		      String item = getItem(position);
		      
		      return mIdMap.get(item);
		    }

		    @Override
		    public boolean hasStableIds() {
		      return true;
		    }

		  }
	 public void onActivityResult (int requestCode, int resultCode, Intent data) {
         if (resultCode == Activity.RESULT_OK) {
             PaymentConfirmation confirm = data.getParcelableExtra(PaymentActivity.EXTRA_RESULT_CONFIRMATION);
             if (confirm != null) {
                 try {
                     Log.i("paymentExample", confirm.toJSONObject().toString(4));

                     // TODO: send 'confirm' to your server for verification.
                     // see https://developer.paypal.com/webapps/developer/docs/integration/mobile/verify-mobile-payment/
                     // for more details.

                 } catch (JSONException e) {
                     Log.e("paymentExample", "an extremely unlikely failure occurred: ", e);
                 }
             }
         }
         else if (resultCode == Activity.RESULT_CANCELED) {
             Log.i("paymentExample", "The user canceled.");
         }
         else if (resultCode == PaymentActivity.RESULT_PAYMENT_INVALID) {
             Log.i("paymentExample", "An invalid payment was submitted. Please see the docs.");
         }
     }
	 @Override
	    public void onDestroy() {
	        stopService(new Intent(getActivity(), PayPalService.class));
	        super.onDestroy();
	    }
	private void stopService(Intent intent) {
		// TODO Auto-generated method stub
		
	}
}
