package com.wireless.apa;


import java.util.ArrayList;
import java.util.Collections;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;


public class ActivityHelper {
	
    private final static String LINEAR_LAYOUT_ID_ROOT = "LinearLayout";
    private final static int ZERO = 0;
    
    public final static String DISABLED = " (disabled)";
    public final static String BUTTON_ID_ROOT = "Button";
    public final static String TEXT_VIEW_ID_ROOT = "TextView";
    public final static String IMAGEBUTTON_ID_ROOT = "ImageButton";
    public final static String DOT_TITLE = ".title";
    public final static String DOT_COUNTER = ".counter";
    public final static String DOT_SRC = ".src";  
    private final static int MAX_NUMBER_OF_ELEMENTS = 12;
    

    public static void dialogText(Activity a, final int _id) {
	
		AlertDialog dialog; 
		String rotation;
		
		final CharSequence[] items = {"CTRL","ALT","SHIFT","TAB","ENTER","ESC","SUPR","DEL","BACK SPACE","SPACE","UP","DOWN"
				,"RIGHT","LEFT","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","U","V","W","X","Y","Z"
				,"1","2","3","4","5","6","7","8","9","10","F1","F2","F3","F4","F5","F6","F7","F8","F9","F10","F11","F12"};
        // arraylist to keep the selected items
        final ArrayList seletedItems=new ArrayList();
		// Declare final variables (to be accessed in onClick)
		final Activity finalActivity = a;
		
		final String id = getFormattedId(_id);			
		

	    AlertDialog.Builder alert = new AlertDialog.Builder(a);
	    
	    if(_id > 0)
	    {
		    TextView tv = null;
			try {
				tv = (TextView) finalActivity.findViewById(R.id.class.getDeclaredField(TEXT_VIEW_ID_ROOT+id).getInt(null));
						        			
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} 
	    
		
			alert.setTitle("Change actual command "+tv.getText()+" by");  
	    }
	    else
	    {
	    	if(_id == -2)
	    		alert.setTitle("Change RIGHT rotation command ("+PropertiesHelper.getInstance().getProperty("AC_RIGHT")+") by");  
	    	
	    	else
	    		alert.setTitle("Change LEFT rotation command ("+PropertiesHelper.getInstance().getProperty("AC_LEFT")+") by");  
	    	
	    	
	    }
	    
	     // Set an EditText view to get user input   
	     final EditText input = new EditText(a);
	     
	     //input.setEnabled(false);
	     input.setTextColor(Color.GREEN);
	     input.setBackgroundColor(Color.BLACK);
	     input.setClickable(false);
	     
	     
	     alert.setMultiChoiceItems(items, null,
                 new DialogInterface.OnMultiChoiceClickListener() {
          // indexSelected contains the index of item (of which checkbox checked)
          @Override
          public void onClick(DialogInterface dialog, int indexSelected,
                  boolean isChecked) {
              if (isChecked) {
                  // If the user checked the item, add it to the selected items
                  // write your code when user checked the checkbox
            	  seletedItems.add(indexSelected);            	  
            	  Collections.sort(seletedItems);
            	  input.setText("");
            	  
            	  for(Object object: seletedItems){
            		  input.append(items[Integer.parseInt(object.toString())]);
            		  input.append(",");
            		}
            	  
            	  input.setText(method(input.getText().toString()));
              } else if (seletedItems.contains(indexSelected)) {
                  // Else, if the item is already in the array, remove it 
                  // write your code when user Uchecked the checkbox
            	  
                  seletedItems.remove(Integer.valueOf(indexSelected));
                  Collections.sort(seletedItems);            	  
                  input.setText("");
            	  
            	  for(Object object: seletedItems){
            		  input.append(items[Integer.parseInt(object.toString())]);
            		  input.append(",");
            		}
            	  
            	  input.setText(method(input.getText().toString()));
              }
          }
      })
       // Set the action buttons
      .setPositiveButton("OK", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int whichButton) {
              //  Your code when user clicked on OK
              //  You can write the code  to save the selected item here
        	String value = input.getText().toString();
  	        
        	if(_id > 0)
	     	{
	        	TextView tv = null;
					try {
						tv = (TextView) finalActivity.findViewById(R.id.class.getDeclaredField(TEXT_VIEW_ID_ROOT+id).getInt(null));
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}    	        
	  	        tv.setText(method(value.toUpperCase()));
     	    
	  	        PropertiesHelper.getInstance().setProperty(IMAGEBUTTON_ID_ROOT+id+DOT_TITLE, value);
	     	}
        	else if(_id == -2)
        		PropertiesHelper.getInstance().setProperty("AC_RIGHT", value); 
	    	else
	    		PropertiesHelper.getInstance().setProperty("AC_LEFT", value);    	    	
        		
        	
        	return;
            
          }
      })
      .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int whichButton) {
             //  Your code when user clicked on Cancel
        	  return;
          }
      });    

	     
	    
	     alert.setView(input);
	     dialog = alert.create();//AlertDialog dialog; create like this outside onClick
         dialog.show();

	}
    
	public static void dialogPort(Activity a, Boolean cancelable) {
		
		// Declare final variables (to be accessed in onClick)
		final Activity finalActivity = a;
		
	    AlertDialog.Builder alert = new AlertDialog.Builder(a);                 
	    alert.setTitle("Change Server Port ("+PropertiesHelper.getInstance().getProperty("PORT")+") by:");  
	    TextView tv = null;
		alert.setCancelable(cancelable);
	     // Set an EditText view to get user input   
	     final EditText input = new EditText(a);	     
	     
	     alert.setView(input);
	     
	     alert.setPositiveButton("Change", new DialogInterface.OnClickListener() {  
	    	 
				public void onClick(DialogInterface dialog, int whichButton) {  
	    	        String value = input.getText().toString();
	    	        	    	        
	    	        PropertiesHelper.getInstance().setProperty("PORT", value);
	    	        
	    	        return;                  
	    	       }  
	    	     });
	     
	     alert.setNegativeButton("No Change", new DialogInterface.OnClickListener() {
	          @Override
	          public void onClick(DialogInterface dialog, int whichButton) {
	             //  Your code when user clicked on Cancel
	        	  return;
	          }
	      });   
	     alert.show();

	}
	
public static void dialogIp(Activity a, Boolean cancelable) {
		
		// Declare final variables (to be accessed in onClick)
		final Activity finalActivity = a;
		
	    AlertDialog.Builder alert = new AlertDialog.Builder(a);                 
	    alert.setTitle("Change Server IP Address ("+PropertiesHelper.getInstance().getProperty("IP")+") by:");  
	    TextView tv = null;
	    alert.setCancelable(cancelable);
	     // Set an EditText view to get user input   
	     final EditText input = new EditText(a);	     
	     
	     alert.setView(input);

	     alert.setPositiveButton("Change", new DialogInterface.OnClickListener() {  
	    	 
				public void onClick(DialogInterface dialog, int whichButton) {  
	    	        String value = input.getText().toString();
	    	        	    	        
	    	        PropertiesHelper.getInstance().setProperty("IP", value);
	    	        return;                  
	    	       }  
	    	     });
	     
	     alert.setNegativeButton("No Change", new DialogInterface.OnClickListener() {
	          @Override
	          public void onClick(DialogInterface dialog, int whichButton) {
	             //  Your code when user clicked on Cancel
	        	  return;
	          }
	      });   
	     alert.show();

	}
    
public static void dialogSpecial(Activity a, int _id)
{
	try {			
		  
		  AlertDialog.Builder builder = new AlertDialog.Builder(a);
		  builder.setTitle("Special Actions");
		  final String id = getFormattedId(_id);
		  final TextView tv = (TextView) a.findViewById(R.id.class.getDeclaredField(ActivityHelper.TEXT_VIEW_ID_ROOT+id).getInt(null));			  
		  
		  CharSequence[] items = {"Shutdown Computer", "Open Spotify", "Return"};
			  builder.setItems(items, new DialogInterface.OnClickListener() {
				  
				    public void onClick(DialogInterface dialog, int item) {
				    	
					      switch(item){
					       case 0:
					    	   tv.setText("SHUTDOWN");
					    	   PropertiesHelper.getInstance().setProperty(IMAGEBUTTON_ID_ROOT+id+DOT_TITLE, "SHUTDOWN");
						     break;
						     
					       case 1:
					    	   tv.setText("SPOTIFY");
					    	   PropertiesHelper.getInstance().setProperty(IMAGEBUTTON_ID_ROOT+id+DOT_TITLE, "SPOTIFY");
					    	 break;						     
					       
					       default:
						    	break;					     
						   
					      } // end switch
					      
					      
				  	        
				            
				    }
				  }); // end onClick...
			  
		   			  
		  
		  builder.setCancelable(true);
		  builder.show();

   } catch(Exception e){}

}
    
    public static String method(String str) {
        if (str.length() > 0 && str.charAt(str.length()-1)==',') {
          str = str.substring(0, str.length()-1);
        }
        return str;
    }
	
	public static void setImagesAndCaptions(Activity a, boolean changeSettings) {
		
        TextView selText = null;
        ImageButton selImageButton = null;        
                
        for (int i=1; i<=MAX_NUMBER_OF_ELEMENTS; i++) {
        	String finalSufix =  getFormattedId(i);
        	
            try {
            	selText = (TextView) a.findViewById(R.id.class.getDeclaredField(TEXT_VIEW_ID_ROOT+finalSufix).getInt(null));
            	selText.setText(PropertiesHelper.getInstance().getProperty(IMAGEBUTTON_ID_ROOT+finalSufix+DOT_TITLE));
            	
            	if (changeSettings) {
	            	if (PropertiesHelper.getInstance().getProperty(IMAGEBUTTON_ID_ROOT+finalSufix+DOT_TITLE).contains(DISABLED)) {            		
			    			LinearLayout ll = (LinearLayout) a.findViewById(R.id.class.getDeclaredField(LINEAR_LAYOUT_ID_ROOT+finalSufix).getInt(null));
			    			ll.setBackgroundResource(R.drawable.disabled_background);	          
	            	} 
            	} // end if changeSettings...
            	
            	selImageButton = (ImageButton) a.findViewById(R.id.class.getDeclaredField(IMAGEBUTTON_ID_ROOT+finalSufix).getInt(null));
            	String imgUrl = PropertiesHelper.getInstance().getProperty(IMAGEBUTTON_ID_ROOT+finalSufix+DOT_SRC);
            	selImageButton.setImageDrawable(Drawable.createFromPath(PropertiesHelper.getInstance().getImagePath() + imgUrl));
            	
            	
			} catch (Exception e) {
				e.printStackTrace();
			} 
			
			
        } 
        
	}
	
	public static void showMessage(Activity a, String message) {
		  AlertDialog.Builder builder = new AlertDialog.Builder(a);
		  builder.setTitle(message);
		  builder.show();		
	}
	
	public static String getFileName(String fullFileName) {
		return fullFileName.substring(fullFileName.lastIndexOf("/")+1, fullFileName.length());
	}
	
	public static String getPath(Activity a, Uri uri) {
		 String[] projection = { android.provider.MediaStore.Images.Media.DATA };
		 Cursor cursor = a.managedQuery(uri, projection, null, null, null);
		 int column_index = cursor.getColumnIndexOrThrow(android.provider.MediaStore.Images.Media.DATA);
		 cursor.moveToFirst();
		 return cursor.getString(column_index);
	}
	
	public static String getFormattedId(int _id) {
    	
		if(_id < 0)
			return Integer.toString(_id);
		else
		{		
			String zero = String.valueOf(ZERO);
	    	String finalId = zero+String.valueOf(_id);
	    	if (finalId.length() > 2)
	    		finalId = finalId.substring(1, 3);   
	    	return finalId;
		}
	}
	
	
}
