package com.sendsms.Parsing;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import org.apache.http.ParseException;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Validations 
{
	public static String regExEmail = "[0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[a-z]{2,4}";
	public static String regExStrChar = "[a-zA-Z ]+";
	public static String regAlphaNumeric = "[a-zA-Z0-9]+";
	public static String regAlphaNumeric1 = "[a-zA-Z0-9_.]+";
	public static String regAlphaNumericpass = "[a-zA-Z0-9]+";
	
	
	public final static Pattern EMAIL_ADDRESS_PATTERN = Pattern.compile(
			"[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" +
					"\\@" +
					"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" +
					"(" +
					"\\." +
					"[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" +
					")+"
			);
	
	
	public static boolean checkEmail(String email) 
	{
		return EMAIL_ADDRESS_PATTERN.matcher(email).matches();
	}
	public static boolean isNumeric(String str)
	{
		return str.matches("-?\\d+(.\\d+)?");
	}
	public static Boolean isValidEmail(String inputEmail) 
	{
		if (!Character.isLetter(inputEmail.charAt(0)))
		{
			return false;
		}
		else 
		{			
			if ( android.util.Patterns.EMAIL_ADDRESS.matcher(inputEmail).matches()) 
			{			
				return true;
			} 
			else 
			{			
				return false;
			}
		}
	}

	public static Boolean isValidChar(String chara)
	{
		Pattern patobj = Pattern.compile(regExStrChar);
		Matcher matobj = patobj.matcher(chara);
		if (matobj.matches()) 
		{
			return true;
		}
		else 
		{
			return false;
		}
	}
	public static Boolean isFullName (String FN)
	{
		return android.util.Patterns.GOOD_IRI_CHAR.matches(FN);
	}

	public static Boolean isValidAlphaNumericChar(String username) 
	{
		if (Character.isDigit(username.charAt(0))) 
		{
			return false;
		}
		else 
		{
			Pattern patobj = Pattern.compile(regAlphaNumeric1);
			Matcher matobj = patobj.matcher(username);
			if (matobj.matches()) 
			{
				return true;
			} 
			else 
			{
				return false;
			}
		}
	}

	public static Boolean isValidAlphaNumericCharForPass(String password) 
	{
		Pattern patobj = Pattern.compile(regAlphaNumeric);
		Matcher matobj = patobj.matcher(password);
		if (matobj.matches()) 
		{
			return true;
		} 
		else 
		{
			return false;
		}
	}
	

	public static void showWarnMessage(Context context, String tStr) {
		Toast toast= Toast.makeText(context , tStr, Toast.LENGTH_LONG);
		toast.setGravity(Gravity.CENTER|Gravity.CENTER_HORIZONTAL, 0, 0);
		toast.show();
	}

	/**
	 * Checking for empty string if it is equal to null, length is zero or containing "null" string 
	 */
	public static boolean isEmptyString(String text) 
	{
		return (text == null ||text.trim().equals("null")|| text.trim().length() <= 0);
	}
	
	/**
	 *  Converts an input stream to string. Used in ServerCommunication class.
	 */
	
	public static boolean hasSpecialCharacter(String text)
	{
		if(isEmptyString(text))
		{
			return false;
		}
		else
		{
			if(text.contains("<")||text.contains(">")||text.contains(";")||text.contains("%")||text.contains("\"")||text.contains("\'")
					||text.contains(",")||text.contains("#")||text.contains("&")||text.contains(":")||text.contains("?")||text.contains("!")
					||text.contains("+")||text.contains("-")||text.contains("=")||text.contains("@")||text.contains("^")||text.contains("*")
					||text.contains("(")||text.contains(")")||text.contains("{")||text.contains("}")||text.contains("[")||text.contains("]"))
			{
				return true;		
			}
			else
			{
				return false;
			}
		}
	}
	
	
	public static boolean isDateInCurrentWeek(Date date) {
		  Calendar currentCalendar = Calendar.getInstance();
		  int week = currentCalendar.get(Calendar.WEEK_OF_YEAR);
		  int year = currentCalendar.get(Calendar.YEAR);
		  Calendar targetCalendar = Calendar.getInstance();
		  targetCalendar.setTime(date);
		  int targetWeek = targetCalendar.get(Calendar.WEEK_OF_YEAR);
		  int targetYear = targetCalendar.get(Calendar.YEAR);
		  return week == targetWeek && year == targetYear;
		}
	public static double roundToDecimalPlaces(String text)
	{
		double value=Double.parseDouble(text);
		
		DecimalFormat df=new DecimalFormat("#.##");
		String formate = df.format(value); 
		try 
		{
			double finalValue = (Double)df.parse(formate);
			return finalValue;
		} 
		catch(ClassCastException e)
		{
			e.printStackTrace();
						
			try 
			{
				double finalValue = (Long)df.parse(formate);
				return finalValue;
			} 
			catch (ParseException e1)
			{
				e1.printStackTrace();
				return value;
			}			
			catch (Throwable t)
			{
				t.printStackTrace();
				return value;
			}
		}
		catch (ParseException e)
		{
			e.printStackTrace();
			return value;			
		}
		catch (Throwable t)
		{
			t.printStackTrace();
			return value;
		}
	}
	
	public static String inputSteamToString(InputStream is) 
	{
		String response;
		StringBuffer responseInBuffer = new StringBuffer();
		byte[] b = new byte[4028];
		try 
		{
			for (int n; (n = is.read(b)) != -1;) 
			{
				responseInBuffer.append(new String(b, 0, n));
			}
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		response = new String(responseInBuffer.toString());
		return response;
	}
	
	/**
	 * Checking if a String matches desired Regex pattern. Used for validating emails.
	 */
	
	public static boolean isMatch(String text, String pattern) 
	{
		try 
		{
			Pattern patt = Pattern.compile(pattern);
			Matcher matcher = patt.matcher(text);
			return matcher.matches();
		}
		catch (RuntimeException e) 
		{
			return false;
		}
	}
	
	/**
	 * Checking if a string contains another string ignoring their case.
	 */
		public static boolean containsIgnoreCaseString(String original, String tobeChecked)
	{
	     return original.toLowerCase().contains(tobeChecked.toLowerCase());
	}
	
	/**
	 * Converts dp to pixels
	 */
	
	public static float convertDpToPixel(float dp,Context context)
	{ 
	    Resources resources = context.getResources();
	    DisplayMetrics metrics = resources.getDisplayMetrics();
	    float px = dp * (metrics.densityDpi/160f);
	    return px;
	}

	/**
	 * Converts pixels to dp
	 */
	
	public static float convertPixelsToDp(float px,Context context)
	{
	    Resources resources = context.getResources();
	    DisplayMetrics metrics = resources.getDisplayMetrics();
	    float dp = px / (metrics.densityDpi / 160f);
	    return dp;
	}
	
	/**
	 * Return a string array containing each chracter of the given string.
	 */
	
	public static String[] breakStringIntoCharacters(String data)
	{
		if(!Validations.isEmptyString(data))
		{
			String output[]=new String[data.length()];
			for(int i=0;i<data.length();i++)
			{
				output[i]=String.valueOf(data.charAt(i));
			}
			return output;
		}	
		else
		{
			return new String[]{};
		}
	}
	
	/**
	 * Get device registered email.	 
	 */
	
	public static String getEmail(Context context) 
	{
	    AccountManager accountManager = AccountManager.get(context); 
	    Account account = getAccount(accountManager);
	    if (account == null) 
	    {
	      return "";
	    }
	    else 
	    {
	      return account.name;
	    }
	}

	/**
	 * Get device account. Used by getEmail() 
	 */
	
	private static Account getAccount(AccountManager accountManager) 
	{
		Account[] accounts = accountManager.getAccountsByType("com.google");
	    Account account;
	    if (accounts.length > 0) 
	    {
	    	account = accounts[0];      
	    } 
	    else 
	    {
	      account = null;
	    }
	    return account;
	}	
	
	/**
	 * Utility method to hide soft keyboard in an activity
	 */
	
	public static void hideSoftKeyboard(Activity activity) 
	{
		try
		{
			/*InputMethodManager inputMethodManager = (InputMethodManager)  activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
		    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);*/
			
			View view = activity.getCurrentFocus();
		    if (view != null) {
		        InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
		        inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		        
		    }
		}	    
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * Utility method to get activity running on top of activity stack.	
	 */
	
	public static String getCurrentTopActivity(Context context) 
    {
        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> RunningTask = mActivityManager.getRunningTasks(1);
        ActivityManager.RunningTaskInfo ar = RunningTask.get(0);
        return ar.topActivity.getClassName().toString();
    }
	
	/**
	 * Utility method to get First letter capital	
	 */
	
	public static String capitalizeFirstLetter(String original)
	{	  		
		try
		{
			if(isEmptyString(original))
		    {
		    	return original;
		    }
			
			String[] tokens = original.split("\\s");
			original = "";

			for(int i = 0; i < tokens.length; i++)
			{
			    char capLetter = Character.toUpperCase(tokens[i].charAt(0));
			    original +=  " " + capLetter + tokens[i].substring(1, tokens[i].length());
			}
			
			return original.trim();
		}		
		catch(Exception e)
		{
			if(isEmptyString(original))
		    {
		    	return original;
		    }
			return original;
		}
	}	

	
	 public static void customDialog(Context ctx,String Message){
		 
		 try {

				
				//dialog.getWindow().setTitle()
			if( !(Validations.isEmptyString(Message))){
				 AlertDialog dialog;
				 Builder builder = new Builder(ctx);
			      builder.setMessage(Message);
			      builder.setCancelable(true);
			      builder.setPositiveButton("OK", new OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						try {
							if(dialog != null)
								dialog.dismiss();
							
						} catch (Exception e) {
							// TODO: handle exception
						}
						
					}
				});
			      dialog = builder.create();
			      dialog.show();
			}
		 
		 
		} catch (Exception e) {
			// TODO: handle exception
		}
	 }
	 
	 
	 
	 
	  public static boolean isNetworkAvailable(Context context) 
		{
			ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = cm.getActiveNetworkInfo();	
			if (networkInfo != null && networkInfo.isConnected()) 
			{
				return true;
			}
			return false;
		} 
	  
		public static Bitmap getRoundedShape(Bitmap scaleBitmapImage) {
			// TODO Auto-generated method stub

			int targetWidth = 80;
			int targetHeight =80;
			Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight,
					Bitmap.Config.ARGB_8888);
			Canvas canvas = new Canvas(targetBitmap);
			Path path = new Path();

			path.addCircle(((float) targetWidth) / 2, ((float) targetHeight) / 2,
					(Math.min(((float) targetWidth), ((float) targetHeight)) / 2),
					Path.Direction.CW);
			Paint paint = new Paint();
			paint.setColor(Color.GRAY);
			// paint.setStyle(Paint.Style.STROKE);
			paint.setStyle(Paint.Style.FILL);
			paint.setAntiAlias(true);
			paint.setDither(true);
			paint.setFilterBitmap(true);
			
			
			canvas.drawOval(new RectF(0, 0, targetWidth, targetHeight), paint);
			canvas.clipPath(path);
			Bitmap sourceBitmap = scaleBitmapImage;

			canvas.drawBitmap(sourceBitmap, new Rect(0, 0, sourceBitmap.getWidth(),
					sourceBitmap.getHeight()), new RectF(0, 0, targetWidth,
					targetHeight), paint);

		

			return targetBitmap;

		}

		public static Bitmap loadImageFromUrl(String url) {
            URL m;
            InputStream i = null;
            BufferedInputStream bis = null;
            ByteArrayOutputStream out =null;
            try {
                m = new URL(url);
                i = (InputStream) m.getContent();
                bis = new BufferedInputStream(i,1024 * 8);
                out = new ByteArrayOutputStream();
                int len=0;
                byte[] buffer = new byte[1024];
                while((len = bis.read(buffer)) != -1){
                    out.write(buffer, 0, len);
                }
                out.close();
                bis.close();
            } catch (MalformedURLException e1) {
                e1.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            byte[] data = out.toByteArray();
            Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
            //Drawable d = Drawable.createFromStream(i, "src");
            return bitmap;
        }
}
