package com.luke.widget;

import android.app.Activity;
import android.appwidget.AppWidgetHostView;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProviderInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.FrameLayout.LayoutParams;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;

import com.luke.widget.WebAppInterface;

import org.apache.cordova.*;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.util.Log;

public class Widget extends CordovaPlugin 
{
	Context context;
	AppWidgetHostView hostView;
	
	AppWidgetManager mAppWidgetManager;
	LauncherAppWidgetHost mAppWidgetHost;

	public static int REQUEST_BIND_APPWIDGET = 1342;
	public static ScrollView sc_view;
	public static LinearLayout main_layout ;
	public static RelativeLayout root_layout ;
	public static int REQUEST_PICK_APPWIDGET = 0;
	public static int REQUEST_CREATE_APPWIDGET = 5;
	public static View current_cordova_webview;
	public static Activity current_cordova_activity;
	public AppWidgetProviderInfo appWidgetInfo = null;
	public static View edit_view;
	public static LinearLayout seekView;
	public static Widget current_obj = null;
	public static Button upButton;
	public static Button downButton;
	public static Button addutton;
	public static boolean show_btn = false;
	public static boolean allow_scroll_in_widget = false;
	public static HashMap< Integer, String > all_widgets = new HashMap< Integer, String >();
	public static int appWidgetId_load;
	public static String current_lang = "";
	public static boolean boolean_wait_for_select = false;
	public static int widget_added = 0;
	public static boolean seek_open = false;
	public static int old_widget_height = 0;
	public static int webviewfull_height = -1;
	
	public static int top_padding = -1;
	public static int bottom_padding = -1;
					
	public static String last_widget_load = "";
	
	// Helper to be compile-time compatible with both Cordova 3.x and 4.x.
    private View getView() 
    {
        try {
            return (View)webView.getClass().getMethod("getView").invoke(webView);
        } catch (Exception e) {
            return (View)webView;
        }
    }
    
	void selectWidget()
	{
		int appWidgetId = this.mAppWidgetHost.allocateAppWidgetId();
		Intent pickIntent = new Intent(AppWidgetManager.ACTION_APPWIDGET_PICK);
		pickIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
		addEmptyData(pickIntent);
		cordova.setActivityResultCallback (this);
		cordova.getActivity().startActivityForResult(pickIntent, REQUEST_PICK_APPWIDGET);
	}

	void addEmptyData(Intent pickIntent)
	{
		ArrayList customInfo = new ArrayList();
		pickIntent.putParcelableArrayListExtra(AppWidgetManager.EXTRA_CUSTOM_INFO, customInfo);
		ArrayList customExtras = new ArrayList();
		pickIntent.putParcelableArrayListExtra(AppWidgetManager.EXTRA_CUSTOM_EXTRAS, customExtras);
	}

	public void createWidget(Intent data) 
	{
		Bundle extras = data.getExtras();
		int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
		AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);

		AppWidgetHostView hostVieww = mAppWidgetHost.createView( context , appWidgetId, appWidgetInfo);
		
		PackageManager pm = cordova.getActivity().getApplicationContext().getPackageManager();
		
		String pn = appWidgetInfo.provider.getPackageName();
		String cn = appWidgetInfo.provider.getClassName();
		String lable = appWidgetInfo.loadLabel(pm);
		
		hostVieww.setAppWidget(appWidgetId, appWidgetInfo);				
		placeWidget(hostVieww , pn , cn , -1 , lable , appWidgetId );				
	}
		
	public void create_seek_bar()
	{
		seek_open = true;
		
		FrameLayout layout = (FrameLayout) webView.getView().getParent();
		
		seekView = new LinearLayout(layout.getContext());
		seekView.setBackgroundColor(Color.TRANSPARENT);
		FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( LayoutParams.FILL_PARENT , LayoutParams.FILL_PARENT );
		
		seekView.setOrientation(LinearLayout.VERTICAL);
		seekView.setLayoutParams(params);
		
		layout.addView(seekView);
		
		WebView webView = new WebView(this.cordova.getActivity().getApplicationContext());
		webView.getSettings().setLoadsImagesAutomatically(true);
		webView.getSettings().setJavaScriptEnabled(true);
		webView.getSettings().setLoadWithOverviewMode(true);
		webView.getSettings().setUseWideViewPort(true);
		webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
		webView.setWebViewClient(new WebViewClient());
		webView.addJavascriptInterface(new WebAppInterface(this.cordova.getActivity().getApplicationContext()), "Android");
		webView.setBackgroundColor(Color.TRANSPARENT);
		webView.setLayoutParams(params);
		
		int edit_view_height = edit_view.getHeight();
		
		int max = 0;
		
		try
		{
			DisplayMetrics displaymetrics = new DisplayMetrics();
			cordova.getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
			int height_real = displaymetrics.heightPixels;
			int width_real = displaymetrics.widthPixels;	
			
			if( height_real > width_real)
			{
				max = height_real;
			}
			else
			{
				max = width_real;
			}
		}
		catch (Exception e) {}
		
		webView.loadUrl("file:///android_asset/www/settings_widget.html?height=" + String.valueOf( edit_view_height ) + "&max=" + String.valueOf( max ) + "&current_lang=" + current_lang );
		
		seekView.addView(webView);
	}
	
	
	
	private void placeWidget(AppWidgetHostView hostView , String in_pn , String in_cn , int in_height , String in_lable , int in_wid)
	{
        main_layout.addView(hostView);
	
		last_widget_load = "";
		
		widget_added = widget_added + 1;
		
		int id_tmp = hostView.generateViewId();
		
		hostView.setId( id_tmp );
		
		String jsonString_tmp = "";
		try
		{
				jsonString_tmp = new JSONObject()
                  .put("pn", in_pn )
                  .put("cn", in_cn )
                  .put("lable" , in_lable)
                  .put("wid" ,String.valueOf( in_wid ))
                  .toString();
        } catch (Exception e) {}
        
		all_widgets.put( id_tmp , jsonString_tmp ); 
		
		int set_height = 100;
		int height_real = 0;
		int width_real  = 0;
		
		if( in_height == -1)
		{
			set_height = 100;
			
			try
			{
				DisplayMetrics displaymetrics = new DisplayMetrics();
				cordova.getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
				height_real = displaymetrics.heightPixels;
				width_real = displaymetrics.widthPixels;	
				
				set_height = height_real;
	
			} catch (Exception e) {}
			
			set_height = set_height - top_padding - bottom_padding;
			set_height = set_height / 2;
							
		}
		else
		{
			set_height = in_height;
		}
	
		hostView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, set_height));
				
        hostView.setOnLongClickListener(new View.OnLongClickListener()
        {
            @Override
            public boolean onLongClick(View view) {
				
				if( seek_open == false)
				{
					int view_height = view.getHeight();
					int view_width = view.getWidth();
						
					old_widget_height = view_height ;
						
					edit_view = view;
						
					create_seek_bar();
				}
                return true;
            }
        });
        
        //Hide Add Button
        cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run()
            {
				try
				{	
					addutton.setVisibility(View.INVISIBLE);
				} catch (Exception e) {}
				
				show_scroll();
            }
			});
		
		boolean_wait_for_select = false;
    }
    
    public static void pass_to_cordova( MotionEvent event)
    {
		current_cordova_activity.runOnUiThread(new Runnable() {
            @Override
            public void run()
            {
				try
				{	
					current_cordova_webview.onTouchEvent(event);
				} catch (Exception e) {}
            }
			});		
	}
	
    public static void close()
    {
		current_cordova_activity.runOnUiThread(new Runnable() {
            @Override
            public void run()
            {
				try
				{	
					((ViewGroup)seekView.getParent()).removeView(seekView);	
				} catch (Exception e) {}
            }
			});
		show_scroll();
		seek_open = false;
	}
	
    public static void reset_view()
    {
		current_cordova_activity.runOnUiThread(new Runnable() {
        @Override
        public void run()
        {
			try
			{
				int view_width = edit_view.getWidth();
					
				edit_view.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, old_widget_height));
				
				((ViewGroup)seekView.getParent()).removeView(seekView);	
		
			} catch (Exception e) {}
        }
		});
		
		seek_open = false;
	}
	
	public static void set_height(int in_height)
    {
		int view_width = edit_view.getWidth();
				
		last_widget_load = "";
		
		current_cordova_activity.runOnUiThread(new Runnable() {
        @Override
        public void run()
        {
			try
			{
					
				edit_view.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, in_height));
		
			} catch (Exception e) {}
        }
		});
		
	}
	
	private void configureWidget(Intent data) 
	{
		Bundle extras = data.getExtras();
		int appWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
		AppWidgetProviderInfo appWidgetInfo = mAppWidgetManager.getAppWidgetInfo(appWidgetId);
		if (appWidgetInfo.configure != null) {
			Intent intent = new Intent(AppWidgetManager.ACTION_APPWIDGET_CONFIGURE);
			intent.setComponent(appWidgetInfo.configure);
			intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
			
			cordova.setActivityResultCallback(this);
			cordova.getActivity().startActivityForResult(intent, REQUEST_CREATE_APPWIDGET);
		} else {
			createWidget(data);
		}
	}


	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
				
		if (resultCode == Activity.RESULT_OK ) {
						
			if (requestCode == REQUEST_PICK_APPWIDGET) {
				configureWidget(data);
			}
			else if (requestCode == REQUEST_CREATE_APPWIDGET) {
				createWidget(data);
			}
			else if (requestCode == REQUEST_BIND_APPWIDGET) {
                createWidget(data);
            }
		}
		else if (resultCode == Activity.RESULT_CANCELED && data != null) {

			int appWidgetId = data.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, -1);
			if (appWidgetId != -1) {
				mAppWidgetHost.deleteAppWidgetId(appWidgetId);
			}
			boolean_wait_for_select = false;
		}
	}
	
	
	public static void hide_element( View in_element)
	{
		current_cordova_activity.runOnUiThread(new Runnable() 
		{
			@Override
			public void run()
			{
				try
				{	
					in_element.setVisibility(View.INVISIBLE);
				} catch (Exception e) {}
			   }
		});
	}
	
	public static void show_element( View in_element)
	{
		current_cordova_activity.runOnUiThread(new Runnable() 
		{
			@Override
			public void run()
			{
				try
				{	
					in_element.setVisibility(View.VISIBLE);
				} catch (Exception e) {}
			   }
		});		
	}
	
	
	public static void add_widget()
	{
		current_obj.selectWidget();
		
		current_cordova_activity.runOnUiThread(new Runnable() {
        @Override
        public void run()
        {
			try
			{	
		
				((ViewGroup)seekView.getParent()).removeView(seekView);
				
			} catch (Exception e) {}
        }
		});	
		
		seek_open = false;
	}
	
	
	
	public static void removeWidget()
	{
		if( ((ViewGroup) main_layout).getChildCount() <= 1)
		{
			show_element(addutton);
		}
		
		current_cordova_activity.runOnUiThread(new Runnable() {
            @Override
            public void run()
            {
				try
				{	
					((ViewGroup)edit_view.getParent()).removeView(edit_view);
	
					((ViewGroup)seekView.getParent()).removeView(seekView);
				
					show_scroll();
				} catch (Exception e) {}
            }
			});	
			
		last_widget_load = "";
		seek_open = false;
	}


	public static void show_scroll()
	{
		if(allow_scroll_in_widget == false)
		{
			show_btn = false;
			return;
		}
		
		if(sc_view.canScrollVertically(-1) == false && sc_view.canScrollVertically(1) == false)
		{
			hide_element(upButton);
			hide_element(downButton);
			show_btn = false;
			return;
		}
	
		show_btn = false;	
			
		if(sc_view.canScrollVertically(-1) == true) //Nach oben geht
		{
			show_element(upButton);
			show_btn = true;
		}
		else //Oder eben nicht.
		{			
			hide_element(upButton);
		}
		
		if(sc_view.canScrollVertically(1) == true) //Nach unten geht
		{
			show_element(downButton);
			show_btn = true;
		}
		else //Oder eben nicht
		{
			hide_element(downButton);
		}
		
	}		
    
    @Override
    public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {

		context = this.cordova.getActivity().getApplicationContext();
		
		current_obj = this;
		
		if (action.equals("hide"))
        {
			hide_element(root_layout);
			
			if( seek_open == true)
			{
				current_cordova_activity.runOnUiThread(new Runnable() {
				@Override
				public void run()
				{
					try
					{	
						((ViewGroup)seekView.getParent()).removeView(seekView);	
					} catch (Exception e) {}
				}
				});
				
				seek_open = false;
			}
		}
	
	
		if (action.equals("show"))
        {
			cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run()
            {
				try
				{	
					root_layout.setVisibility(View.VISIBLE);
			
				} catch (Exception e) {}
				
				try
				{	
					root_layout.setAlpha(1); 
				} catch (Exception e) {}
				
            }
			});	
		}

	
		if (action.equals("padding"))
        {
			cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run()
            {
				try
				{	
					String top = data.getString(0);
					String bottom = data.getString(1);
					String full = data.getString(2);
					
					top_padding = Integer.parseInt(top);
					bottom_padding = Integer.parseInt(bottom);					
					webviewfull_height = Integer.parseInt(full);		
					
					DisplayMetrics displaymetrics = new DisplayMetrics();
					cordova.getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
					int height_real = displaymetrics.heightPixels;
					
					double fak = 0;
					
					if(height_real > webviewfull_height )
					{
						fak = Double.valueOf(height_real) / Double.valueOf(webviewfull_height) ;
					}
					else
					{
						fak = Double.valueOf(webviewfull_height) / Double.valueOf(height_real)  ;
					}
					
					if( fak != 0 )
					{
						top_padding =  (int) (Double.valueOf(top_padding) * fak);
						bottom_padding =  (int) (Double.valueOf(bottom_padding) * fak);
					}
					
					root_layout.setPadding(0,top_padding,0,bottom_padding);
					
					show_scroll();
					
				} catch (Exception e) {}
            }
			});	
		}
			
		
		if (action.equals("transparency"))
        {
			cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run()
            {
				try
				{	
					try
					{	
						root_layout.setVisibility(View.VISIBLE);
					} catch (Exception e) {}
					
					String settrans = data.getString(0);					
					float settrans_float = Float.parseFloat(settrans) / 100;
					root_layout.setAlpha(settrans_float); 
					
				} catch (Exception e) {}
            }
			});	
		}	
		

		if (action.equals("save"))
        {
			String save_string = "";
			
			for (int i = 0; i < main_layout.getChildCount(); i++)
			{
				View current_view = main_layout.getChildAt(i);
	
				String json_string = all_widgets.get(current_view.getId());
				
				JSONObject mainjsonobject = new JSONObject(json_string);
				
				String pn = mainjsonobject.getString("pn");  
				String cn = mainjsonobject.getString("cn");
				String lable = mainjsonobject.getString("lable");
				String height = String.valueOf(current_view.getHeight());
				String wid = mainjsonobject.getString("wid");
				
				save_string = save_string +  pn + "!#!" + cn + "!#!" + height + "!#!" + lable + "!#!" + wid + "!!#!!";	
			}
			callbackContext.success(save_string);
		}	
		
		
		if (action.equals("destroy"))
        {
					
			if( mAppWidgetHost != null)
			{
				
				Runnable clear_widget_thread = new Runnable()
				{
					@Override
					public void run()
					{	
						//Clear the view...
						try
						{
							((LinearLayout) main_layout).removeAllViews(); 
						}
						catch(Exception e) {}
				
						synchronized(this){ this.notify(); }
					}
				};
						
				try
				{
					synchronized( clear_widget_thread )
					{
						cordova.getActivity().runOnUiThread(clear_widget_thread) ;
						clear_widget_thread.wait(); 
					}
				}
				catch(Exception e) {}
						
				cordova.getActivity().runOnUiThread(new Runnable() {
				@Override
				public void run()
				{
					try
					{
						((ViewGroup)root_layout.getParent()).removeView(root_layout);
					}
					catch (Exception e){}
					
					try
					{
						mAppWidgetHost.stopListening();
					}
					catch (Exception e){}
					mAppWidgetHost = null;
				}
				});	
			}
			
			callbackContext.success("ok");
						
		}	
		
		
		if (action.equals("load"))
        {	
			widget_added = 0;
			
			String load_string_tmp = data.getString(0);
			
			if( last_widget_load.equals(load_string_tmp) == false || load_string_tmp.equals("") )
			{
		
				Runnable clear_widget_thread = new Runnable()
				{
					@Override
					public void run()
					{	
						//Clear the view...
						 ((LinearLayout) main_layout).removeAllViews(); 
						synchronized(this){ this.notify(); }
					}
				};
				
				try
				{
					synchronized( clear_widget_thread )
					{
					   cordova.getActivity().runOnUiThread(clear_widget_thread) ;
					   clear_widget_thread.wait(); 
					}
				}
				catch(Exception e) {}
				
				
				String load_string = data.getString(0);
				load_string = load_string.trim()+"";					
				String[] load_array = load_string.split("!!#!!");
						
				//Clear the Hash map
				all_widgets.clear();
				
				for (int ccc = 0; ccc < load_array.length; ccc++)
				{
				
					if( load_array[ccc] != "" )
					{
						String[] load_array_sub = load_array[ccc].split("!#!");

						String pn_load_tmp = load_array_sub[0];
						String cn_load_tmp = load_array_sub[1];
						String height_load = load_array_sub[2];		
						String lable_load = load_array_sub[3];		 
						String wid_s = load_array_sub[4];

						ComponentName cn = new ComponentName(pn_load_tmp,cn_load_tmp);

						appWidgetId_load =  Integer.parseInt(wid_s);
						boolean allowed_to_bind = mAppWidgetManager.bindAppWidgetIdIfAllowed(appWidgetId_load, cn);

						// Ask the user to allow this app to have access to their widgets
						if (allowed_to_bind)
						{
							Intent i = new Intent(AppWidgetManager.ACTION_APPWIDGET_BIND);
							Bundle args = new Bundle();
							args.putInt(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId_load);
							args.putParcelable(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER, cn);
							args.putParcelable(AppWidgetManager.EXTRA_APPWIDGET_PROVIDER_PROFILE, null);
							i.putExtras(args);
							cordova.setActivityResultCallback(this);
							cordova.getActivity().startActivityForResult(i, REQUEST_BIND_APPWIDGET);
						} 
						else 
						{			
							final List<AppWidgetProviderInfo> infos = mAppWidgetManager.getInstalledProviders();
							  
							for (final AppWidgetProviderInfo info : infos) 
							{
								if (info.provider.getClassName().equals(cn.getClassName()) && info.provider.getPackageName().equals(cn.getPackageName()))
								{
									appWidgetInfo = info;
									break;
								}
							}
							
							if (appWidgetInfo != null) 
							{
								Runnable add_thread = new Runnable()
								{
									@Override
									public void run()
									{
										try
										{	
											AppWidgetHostView hostView = mAppWidgetHost.createView(cordova.getActivity().getBaseContext(), appWidgetId_load, appWidgetInfo);
											hostView.setAppWidget(appWidgetId_load, appWidgetInfo);

											String pn = appWidgetInfo.provider.getPackageName();
											String cn = appWidgetInfo.provider.getClassName();
						
											PackageManager pm = cordova.getActivity().getApplicationContext().getPackageManager();
											String lable = appWidgetInfo.loadLabel(pm);
											
											placeWidget(hostView , pn , cn , Integer.parseInt( height_load ) ,lable , appWidgetId_load);
											
											synchronized(this){ this.notify(); }
										} 
										catch (Exception e)
										{
											synchronized(this){ this.notify(); }
										}
									}
								};
								
								try
								{
									synchronized( add_thread )
									{
									   cordova.getActivity().runOnUiThread(add_thread) ;
									   add_thread.wait(); 
									}
								}
								catch(Exception e) {}
							}
						}
					}
				}
			
				if( widget_added == 0)
				{
					current_cordova_activity.runOnUiThread(new Runnable() {
						@Override
						public void run()
						{
							try
							{	
								addutton.setVisibility(View.VISIBLE);
							} catch (Exception e) {}
						}
						});
				}
			
				last_widget_load = load_string_tmp;
			}
		
		callbackContext.success("ok");	
			
		}
		
		
		if (action.equals("add_widget_settings"))
        {	
			boolean_wait_for_select = true;
			selectWidget();
			
			while(true)
			{
				if(boolean_wait_for_select == false)
				{
					break;
				}
				
				try
				{
					Thread.sleep(50);
				}
				catch(Exception e ){}
			}
			callbackContext.success("ok");
		}
		
			
		//Creates the Widget view...		
        if (action.equals("create"))
        {
			cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run()
            {
				try
				{
					String widget_up_text = "";
					String widget_down_text = "";
					String widget_add_text  = "";
					
					try
					{
						String translate_json = data.getString(4);
						JSONObject translate_json_obj = new JSONObject(translate_json);	
						widget_up_text = translate_json_obj.getString("widget_up");  
						widget_down_text = translate_json_obj.getString("widget_down");
						widget_add_text = translate_json_obj.getString("widget_add");
						current_lang = translate_json_obj.getString("current_lang");
					}
					catch (Exception e){}
							
					String allow_scroll_in_widget_s = data.getString(3);
					if( allow_scroll_in_widget_s.equals("1") == true)
					{
						allow_scroll_in_widget = true;
					}
					else
					{
						allow_scroll_in_widget = false;
					}
					
												
					if( mAppWidgetHost == null)
					{
						sc_view = new ScrollView(context);
						sc_view.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
						
						sc_view.setFillViewport(true);
						sc_view.setVerticalScrollBarEnabled(false);
						sc_view.setHorizontalScrollBarEnabled(false);
												
						FrameLayout layout = (FrameLayout) webView.getView().getParent();
						
						current_cordova_webview = webView.getView();
						current_cordova_activity = cordova.getActivity();

						root_layout = new RelativeLayout(context);
						//root_layout.setOrientation(LinearLayout.VERTICAL);
						root_layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
						
						layout.addView(root_layout);
												
						downButton = new Button(context);
						downButton.setText(widget_down_text);	
						downButton.setBackgroundColor(Color.WHITE);	
						downButton.setTextColor(Color.BLACK);	
						
						downButton.setMinHeight(0);
						downButton.setMinimumHeight(0);
						downButton.setAlpha(0.82f); 
						
						downButton.setOnClickListener(new OnClickListener() {
							public void onClick(View v) {
								
								DisplayMetrics displaymetrics = new DisplayMetrics();
								cordova.getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
								int height_real = displaymetrics.heightPixels;
								height_real = height_real / 3;
								
								sc_view.smoothScrollBy(0, height_real);
								show_scroll();
							}
						});
						
						RelativeLayout.LayoutParams centerRel = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
						centerRel.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); //CENTER_IN_PARENT);
						downButton.setLayoutParams(centerRel);
						root_layout.addView(downButton);
							
						upButton = new Button(context);
						upButton.setText(widget_up_text);	
						upButton.setBackgroundColor(Color.WHITE);	
						upButton.setTextColor(Color.BLACK);	
						
						upButton.setMinHeight(0);
						upButton.setMinimumHeight(0);
						upButton.setAlpha(0.82f); 
						 						
						upButton.setOnClickListener(new OnClickListener() {
							public void onClick(View v) {
								
								DisplayMetrics displaymetrics = new DisplayMetrics();
								cordova.getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
								int height_real = displaymetrics.heightPixels;
								height_real = height_real / 3;
								
								sc_view.smoothScrollBy(0, -height_real );
								show_scroll();
							}
						});
						
						RelativeLayout.LayoutParams centerRel2 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
						centerRel2.addRule(RelativeLayout.ALIGN_PARENT_TOP); //CENTER_IN_PARENT);
						upButton.setLayoutParams(centerRel2);
						root_layout.addView(upButton);
						
						show_scroll();
						
						root_layout.addView(sc_view);
						
						main_layout = new LinearLayout(context);
						main_layout.setOrientation(LinearLayout.VERTICAL);
						main_layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
						
						sc_view.addView(main_layout);
						
						mAppWidgetManager = AppWidgetManager.getInstance(context);
						mAppWidgetHost = new LauncherAppWidgetHost(context, 4242);
						mAppWidgetHost.startListening();
						
						addutton = new Button(context);
						addutton.setText(widget_add_text);	
						addutton.setBackgroundColor(Color.WHITE);
						addutton.setTextColor(Color.BLACK);					
						addutton.setOnClickListener(new OnClickListener() {
							public void onClick(View v) {
								selectWidget();
							}
						});
						
						RelativeLayout.LayoutParams centerRel3 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
						centerRel3.addRule(RelativeLayout.CENTER_IN_PARENT); 
						addutton.setLayoutParams(centerRel3);
						root_layout.addView(addutton);
						
						sc_view.setOnTouchListener(new OnTouchListener()
						{ 
							@Override 
							public boolean onTouch(View v, MotionEvent event) 
							{ 
								webView.getView().onTouchEvent(event);
								return false; 
							} 
						}); 
						
						//Padding
						String top = data.getString(0);
						String bottom = data.getString(1);
						String full = data.getString(2);
					
						top_padding = Integer.parseInt(top);
						bottom_padding = Integer.parseInt(bottom);					
						
						webviewfull_height = Integer.parseInt(full);		
						
						DisplayMetrics displaymetrics = new DisplayMetrics();
						cordova.getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
						int height_real = displaymetrics.heightPixels;
						
						double fak = 0;
						
						if(height_real > webviewfull_height )
						{
							fak = Double.valueOf(height_real) / Double.valueOf(webviewfull_height) ;
						}
						else
						{
							fak = Double.valueOf(webviewfull_height) / Double.valueOf(height_real)  ;
						}
						
						if( fak != 0 )
						{
							top_padding =  (int) (Double.valueOf(top_padding) * fak);
							bottom_padding =  (int) (Double.valueOf(bottom_padding) * fak);
						}
						
						root_layout.setPadding(0,top_padding,0,bottom_padding);

						try
						{	
							root_layout.setVisibility(View.INVISIBLE);
						} catch (Exception e){ callbackContext.success("fail"); }
						
						
						if( allow_scroll_in_widget == true)
						{			
							show_element(upButton);
							show_element(downButton);
						}
						else
						{
							hide_element(upButton);
							hide_element(downButton);
						}
						
						callbackContext.success("ok");
					}
					else
					{
						
						if( allow_scroll_in_widget == true)
						{
							show_element(upButton);
							show_element(downButton);
						}
						else
						{
							hide_element(upButton);
							hide_element(downButton);
						}
						
						try
						{
							addutton.setText(widget_add_text);
							upButton.setText(widget_up_text);
							downButton.setText(widget_down_text);
						}
						catch (Exception e){ callbackContext.success("fail"); }
						
						callbackContext.success("ok");
					}
		
				} catch (Exception e){ callbackContext.success("fail"); }
            }
			});

            return true;
        }
        else 
        {    
            return false;
        }
    }
}
