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 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;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
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 android.widget.Button;
 

public class askquestion extends Fragment {
	
	 
	public askquestion(){}
	  EditText mEdit;
	Spinner mDrawerList,mDrawerList1; 
	  EditText timer;
		EditText edittext;
		WebView webView;
		RadioButton male,female;
		Button btn;
		 EditText firstname,lastname,city,state,date,time,email,pcity,pstate,quest;
		 RadioGroup sex;
		Spinner precountry,country;
		 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"; 

		 
		 @Override
	    public View onCreateView(LayoutInflater inflater,
	    ViewGroup container, Bundle savedInstanceState)
	    {
	        final View InputFragmentView = inflater.inflate(
	            R.layout.askquestion_layout, container, false);
			 
	        webView = (WebView)InputFragmentView.findViewById(R.id.myview); 
	        
	        final AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
	        
	     firstname=(EditText)InputFragmentView.findViewById(R.id.firstname);
	     lastname=(EditText)InputFragmentView.findViewById(R.id.lastname);
	     city=(EditText)InputFragmentView.findViewById(R.id.city);
	     state=(EditText)InputFragmentView.findViewById(R.id.state);
	     date=(EditText)InputFragmentView.findViewById(R.id.dateofbirth);
	     time=(EditText)InputFragmentView.findViewById(R.id.timeofbirth);
	     email=(EditText)InputFragmentView.findViewById(R.id.email);
	     pcity=(EditText)InputFragmentView.findViewById(R.id.precity);
	     pstate=(EditText)InputFragmentView.findViewById(R.id.prestate);
	    quest=(EditText)InputFragmentView.findViewById(R.id.question);
	    sex=(RadioGroup)InputFragmentView.findViewById(R.id.sex);
	     
	     precountry=(Spinner)InputFragmentView.findViewById(R.id.spinner1);
	     country=(Spinner)InputFragmentView.findViewById(R.id.spinner2);
		    
	     male=(RadioButton)InputFragmentView.findViewById(R.id.m);
	
	        btn = (Button)InputFragmentView.findViewById(R.id.button1);
	        btn.setOnClickListener(new View.OnClickListener() {
	            @Override
	            public void onClick(View v) {
	            	
	            	  String user = email.getText().toString();
	            	  String first=firstname.getText().toString();
	            	  String last=lastname.getText().toString();
	            	  String cit=city.getText().toString();
	            	  String stat=state.getText().toString();
	            	  String coun=country.getSelectedItem().toString();
	            	  String dat=date.getText().toString();
	            	  String itm=time.getText().toString();
	            	  String pcit=pcity.getText().toString();
	            	  String psta=pstate.getText().toString();
	            	  String ques=quest.getText().toString();
	            	  String presentcoun=precountry.getSelectedItem().toString();
	            	
	            	  
	            	//getting the id of selected radio button 
	                  int value = sex.getCheckedRadioButtonId();
	                  String gen;
	                  //checking the id of the selected radio
	                  if(value == male.getId())
	                  {
	                      gen="Male";
	                  }
	                  else
	                  {
	                    gen="Female";
	                  }
	            	  
	            	   	String format= "First Name :" +first +"<br />"
		            	+"Last Name :" +last + "<br />"
		            	+"Gender : "+gen + "<br/>"
		            	+"City : " +cit + "<br/>"
		            	+"State/Province : " +stat + "<br/>"
		            	+"Country of Birth : " +coun + "<br/>"
		            	+"Date of Birth : " +dat + "<br/>"
		            	+"Time of Birth : " +itm + "<br/>"
		            	+"Present Country : " +presentcoun + "<br/>"
		            	+"E-mail Address : " +user + "<br/>"
		            	+"Present City : " +pcit + "<br/>"
		            	+"Present state : " +psta + "<br/>"
		            	+"Question : " +ques + "<br/>"
		            	+"Details : PayPal - USD 10 "+ "<br/>";
		            	
		            	  
	            	if( firstname.getText().toString().length() == 0 )
	            	{
	            		 alt_bld.setTitle("Alert Message");
	            		 alt_bld.setMessage(" Enter your Firstname")
	            		 .setCancelable(false)
	            					 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
	            					 public void onClick(DialogInterface dialog, int id) {
	            						 firstname.requestFocus(); 
	            					 }
	            					 });
	            		 AlertDialog alert = alt_bld.create();
	            		 alert.setTitle("Alert Message");
	            		 alert.setIcon(R.drawable.alert);
	            		 alert.show();
	            		 firstname.setFocusable(true);
	            	}
	            	else if( lastname.getText().toString().length() == 0 )
	            	{
	            		 alt_bld.setTitle("Alert Message");
	            		 alt_bld.setMessage(" Enter your Lastname")
	            		 .setCancelable(false)
	            					 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
	            					 public void onClick(DialogInterface dialog, int id) {
	            						 lastname.requestFocus(); 
	            					 }
	            					 });
	            		 AlertDialog alert = alt_bld.create();
	            		 alert.setTitle("Alert Message");
	            		 alert.setIcon(R.drawable.alert);
	            		 alert.show();
	            		 lastname.setFocusable(true);
	            	}
	            	
	            	else if( city.getText().toString().length() == 0 )
	            	{
	            		 alt_bld.setTitle("Alert Message");
	            		 alt_bld.setMessage(" Enter your city")
	            		 .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("Enter your state")
	            		 .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(country.getSelectedItem().toString().length() == 0)
	            	{
	            		 alt_bld.setTitle("Alert Message");
	            		 alt_bld.setMessage(" Enter your country name")
	            		 .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( date.getText().toString().length() == 0 )
	            	{
	            		 alt_bld.setTitle("Alert Message");
	            		 alt_bld.setMessage("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("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( precountry.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) {
	            						 precountry.requestFocus(); 
	            					 }
	            					 });
	            		 AlertDialog alert = alt_bld.create();
	            		 alert.setTitle("Alert Message");
	            		 alert.setIcon(R.drawable.alert);
	            		 alert.show();
	            		 precountry.setFocusable(true);
	            	}
	            	else if( email.getText().toString().length() == 0 )
	            	{
	            		 alt_bld.setTitle("Alert Message");
	            		 alt_bld.setMessage("Please enter your 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( pcity.getText().toString().length() == 0 )
	            	{
	            		 alt_bld.setTitle("Alert Message");
	            		 alt_bld.setMessage("Please enter your present city")
	            		 .setCancelable(false)
	            					 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
	            					 public void onClick(DialogInterface dialog, int id) {
	            						 pcity.requestFocus(); 
	            					 }
	            					 });
	            		 AlertDialog alert = alt_bld.create();
	            		 alert.setTitle("Alert Message");
	            		 alert.setIcon(R.drawable.alert);
	            		 alert.show();
	            		 pcity.setFocusable(true);
	            	}
	            	else if( pstate.getText().toString().length() == 0 )
	            	{
	            		 alt_bld.setTitle("Alert Message");
	            		 alt_bld.setMessage("Please enter your present state")
	            		 .setCancelable(false)
	            					 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
	            					 public void onClick(DialogInterface dialog, int id) {
	            						 pstate.requestFocus(); 
	            					 }
	            					 });
	            		 AlertDialog alert = alt_bld.create();
	            		 alert.setTitle("Alert Message");
	            		 alert.setIcon(R.drawable.alert);
	            		 alert.show();
	            		 pstate.setFocusable(true);
	            	}
	            	
	            	else if(quest.getText().toString().length() == 0 )
	            	{
	            		 alt_bld.setTitle("Alert Message");
	            		 alt_bld.setMessage("Please enter your Additional  questions")
	            		 .setCancelable(false)
	            					 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
	            					 public void onClick(DialogInterface dialog, int id) {
	            						 quest.requestFocus(); 
	            					 }
	            					 });
	            		 AlertDialog alert = alt_bld.create();
	            		 alert.setTitle("Alert Message");
	            		 alert.setIcon(R.drawable.alert);
	            		 alert.show();
	            		 quest.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( !(firstname.getText().toString().length() == 0) || !(lastname.getText().toString().length() == 0) ||!(city.getText().toString().length() == 0) ||!(state.getText().toString().length() == 0) || !(country.getSelectedItem().toString().length() == 0)||!(date.getText().toString().length() == 0)||!(time.getText().toString().length() == 0)|| ! precountry.getSelectedItem().toString().equals("--Select--")||!(email.getText().toString().length() == 0)|| !(pcity.getText().toString().length() == 0)|!(pstate.getText().toString().length() == 0)||!(quest.getText().toString().length() == 0)    )
	            	{
	            		
	            		 try {   
                      	   
	            			 GMailSender sender = new GMailSender(user,format,"Ask a Question - 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", "Ask a Question- 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
					
				}

	           
	            
	          });
       		
	          edittext=(EditText)InputFragmentView .findViewById(R.id.dateofbirth); 
	        timer=(EditText)InputFragmentView .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);

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

	        };

	           edittext.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() {
		                     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();

		             }
		         });

		       
	        mDrawerList = (Spinner)InputFragmentView.findViewById(R.id.spinner1);  
	        
	        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);
	         
	         mDrawerList.setAdapter(adapter);
	         
	         mDrawerList1 = (Spinner)InputFragmentView.findViewById(R.id.spinner2);  
		        
		        String[] items1 = getResources().getStringArray(R.array.country_array);
		      
		        
		        final ArrayList<String> list1 = new ArrayList<String>();
		         for (int i = 0; i < items1.length; ++i) {
		           list1.add(items1[i]);
		         }
		        
		          
		         final StableArrayAdapter adapter1 = new StableArrayAdapter(getActivity(),android.R.layout.simple_spinner_dropdown_item, list);
		         
		         mDrawerList1.setAdapter(adapter1);
		        
		     
		      return InputFragmentView;  
	           }  
	
			// TODO Auto-generated method stub
			
			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.");
                 getActivity().finish();
                 Intent int_spa = new Intent(getActivity(),ourservices.class);
    	            int_spa.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    	            startActivity(int_spa);
             }
             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(), MainActivity.class));
		        super.onDestroy();
		    }
		private void stopService(Intent intent) {
			// TODO Auto-generated method stub
			
		}
}
		
		 
		 