package astrology.findyourfate.com;
import java.io.File;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
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.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
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.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;


public class vastu extends Fragment {
	
	public vastu(){}
	EditText dat;
	  EditText firstname,lastname,email,conemail,mEdit;
		 RadioGroup pay;
		 Button btn;  
		 File downloadedPic = null;
		 WebView webView;
		 File pic;
	    private ImageView attachImage = null;
	    private byte[] image = null;
	    private static final int SELECT_IMAGE = 1;
	    String path;
private static final String CONFIG_ENVIRONMENT = PaymentActivity.ENVIRONMENT_NO_NETWORK;
	    
	    // note that these credentials will differ between live & sandbox environments.
	    private static final String CONFIG_CLIENT_ID = "GB7QEWLT4JRQ6";
	    // when testing in sandbox, this is likely the -facilitator email address. 
	    private static final String CONFIG_RECEIVER_EMAIL = "stanley@findyourfate.com"; 

    
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
 
     View view = inflater.inflate(R.layout.vastu, container, false);
     attachImage= (ImageView)view.findViewById(R.id.imageView1);
     webView = (WebView)view.findViewById(R.id.myview); 
     btn = (Button)view.findViewById(R.id.payment); 
          
     firstname=(EditText)view.findViewById(R.id.firstname);
     lastname=(EditText)view.findViewById(R.id.lastname);
     email=(EditText)view.findViewById(R.id.email);
     conemail=(EditText)view.findViewById(R.id.cemail);
     	     pay=(RadioGroup)view.findViewById(R.id.payable);
 
	   
     	    final AlertDialog.Builder alt_bld = new AlertDialog.Builder(getActivity());
		       
		   
    	    ((Button)view.findViewById(R.id.btn_select))
    	    .setOnClickListener(new OnClickListener() {
    	        public void onClick(View arg0) {
    	        	Intent intent = new Intent(Intent.ACTION_GET_CONTENT).setType("image/*");
                    startActivityForResult(intent, SELECT_IMAGE);
    	        }
    	    });
    	    
    	    btn.setOnClickListener(new OnClickListener() {
    	        public void onClick(View arg0) {
    	          	 
    	        	
    	        	  String user = email.getText().toString();
    	        	  String fname=firstname.getText().toString();
	            	  String lname=lastname.getText().toString();
	            	  String cemail=conemail.getText().toString();
	            	
	            	  
	            	  
		            	if(firstname.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) {
		            						 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("Please enter your last name")
		            		 .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();
		            		 lastname.setFocusable(true);
		            	}
    	        	
		            	else if(email.getText().toString().length() == 0 )
		            	{
		            		 alt_bld.setTitle("Alert Message");
		            		 alt_bld.setMessage("Please enter your 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(conemail.getText().toString().length() == 0 )
		            	{
		            		 alt_bld.setTitle("Alert Message");
		            		 alt_bld.setMessage("Please enter your confirmation email address")
		            		 .setCancelable(false)
		            					 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
		            					 public void onClick(DialogInterface dialog, int id) {
		            						 conemail.requestFocus(); 
		            					 }
		            					 });
		            		 AlertDialog alert = alt_bld.create();
		            		 alert.setTitle("Alert Message");
		            		 alert.setIcon(R.drawable.alert);
		            		 alert.show();
		            		 conemail.setFocusable(true);
		            	}
		            	else if(attachImage.getDrawable()==null)
		            			
		            	{
		            		 alt_bld.setTitle("Alert Message");
		            		 alt_bld.setMessage("Please upload your Building plan")
		            		 .setCancelable(false)
		            					 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
		            					 public void onClick(DialogInterface dialog, int id) {
		            						 attachImage.requestFocus(); 
		            					 }
		            					 });
		            		 AlertDialog alert = alt_bld.create();
		            		 alert.setTitle("Alert Message");
		            		 alert.setIcon(R.drawable.alert);
		            		 alert.show();
		            		 attachImage.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(!(conemail.getText().toString().length() == email.getText().toString().length()))
		            						            	{
		            		 alt_bld.setTitle("Alert Message");
		            		 alt_bld.setMessage("Please enter correct confirmation email address")
		            		 .setCancelable(false)
		            					 .setPositiveButton("OK", new DialogInterface.OnClickListener() {
		            					 public void onClick(DialogInterface dialog, int id) {
		            						conemail.requestFocus(); 
		            					 }
		            					 });
		            		 AlertDialog alert = alt_bld.create();
		            		 alert.setTitle("Alert Message");
		            		 alert.setIcon(R.drawable.alert);
		            		 alert.show();
		            		 conemail.setFocusable(true);
		            	}	
		           	
		            	else if( !(firstname.getText().toString().length() == 0) || !(lastname.getText().toString().length() == 0)||!(email.getText().toString().length() == 0) || !(conemail.getText().toString().length() == 0) || !(attachImage.getDrawable()==null) )
		            	{
		            		
		            	  	 	 String format= "First Name :" +fname +"<br />"
		     		            	+"Last Name :" +lname + "<br />"
		     		            	+"E-mail Address : " +user + "<br/>"
		     		            	+"Confirm E-mail Address : " +cemail + "<br/>"
		     		        		+"Details :PayPal - USD 50" + "<br/>" ;
		            	  	 	 
		            	  	 	 
		 try {   
		                        	   
 GMailSender sender = new GMailSender(user,format,"Vastu - Confirmation Details  - findyourfate.com apps", path );
	//	 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("50.00"), "USD", "Vastu -  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
					
				}
			    	    });
    	    
    	    mEdit=(EditText)view.findViewById(R.id.dateofbirth); 
    	    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();
	                }
	            });
    	    
    	    return view;
    	}

    	//UPDATED
    	@Override
    	public void onActivityResult(int requestCode, int resultCode, Intent data) {
    		 super.onActivityResult(requestCode, resultCode, data);
    	    if (resultCode == Activity.RESULT_OK) {
    	        if (requestCode == SELECT_IMAGE) {
    	            
    	            Uri selectedImageUri = data.getData();
    	            //OI FILE Manager
    	          String  filemanagerstring = selectedImageUri.getPath();

    	            //MEDIA GALLERY
    	           String  selectedImagePath = getPath(selectedImageUri);

    	             
                    if (selectedImagePath != null) {
                        path = selectedImagePath;
                    } else {
                        path = filemanagerstring;
                    }
                    
                    Util.debug("Imagepath: '" + path + "'.");
                    Bitmap bitmap = Util.decodeBitmap(path, 800);
                    image = Util.bitmapToBytes(bitmap);
                    attachImage.setImageBitmap(bitmap);
                   	        }
                   
      else
    	        	{
    	        	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(), PayPalService.class));
		        super.onDestroy();
		    }
		private void stopService(Intent intent) {
			// TODO Auto-generated method stub
			
		}
    	  private String getPath(Uri uri) {
    	        String[] projection = {MediaStore.Images.Media.DATA};
    	        Cursor cursor = getActivity().managedQuery(uri, projection, null, null, null);
    	        if (cursor != null) {
    	              int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    	            cursor.moveToFirst();
    	            return cursor.getString(column_index);
    	        } else {
    	            return null;
    	        }
    	    }
    	}