package com.jens.automation2;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.jens.automation2.Action.Action_Enum;

import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Map;

public class ActivityManageActionTriggerUrl extends Activity
{
	Button bSaveTriggerUrl, bAddHttpParam;
	EditText etTriggerUrl, etTriggerUrlUsername, etTriggerUrlPassword, etParameterName, etParameterValue;
	ListView lvTriggerUrlPostParameters;
	CheckBox chkTriggerUrlUseAuthentication;
	RadioButton rbTriggerUrlMethodGet, rbTriggerUrlMethodPost;
	TableLayout tlTriggerUrlAuthentication;
	TextView tvHttpParameterExplanation;
	ArrayAdapter<String> httpParametersAdapter;

	private ArrayList<String> httpParamsList = new ArrayList<>();
	ArrayAdapter<Map<String,String>> lvTriggerUrlPostParametersAdapter;

	public static final String methodGet = "GET";
	public static final String methodPost = "POST";
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		Miscellaneous.setDisplayLanguage(this);
		Miscellaneous.setUiTheme(this);
		this.setContentView(R.layout.activity_manage_action_trigger_url);
		
		etTriggerUrl = (EditText)findViewById(R.id.etTriggerUrl);
		etTriggerUrlUsername = (EditText)findViewById(R.id.etTriggerUrlUsername);
		etTriggerUrlPassword = (EditText)findViewById(R.id.etTriggerUrlPassword);
		chkTriggerUrlUseAuthentication = (CheckBox)findViewById(R.id.chkTriggerUrlUseAuthentication);
		lvTriggerUrlPostParameters = (ListView)findViewById(R.id.lvTriggerUrlPostParameters);
		tlTriggerUrlAuthentication = (TableLayout)findViewById(R.id.tlTriggerUrlAuthentication);
		bSaveTriggerUrl = (Button)findViewById(R.id.bSaveSpeakText);
		rbTriggerUrlMethodGet = (RadioButton) findViewById(R.id.rbTriggerUrlMethodGet);
		rbTriggerUrlMethodPost = (RadioButton) findViewById(R.id.rbTriggerUrlMethodPost);
		etTriggerUrl = (EditText) findViewById(R.id.etTriggerUrl);
		etParameterName = (EditText) findViewById(R.id.etParameterName);
		etParameterValue = (EditText)findViewById(R.id.etParameterValue);
		bAddHttpParam = (Button)findViewById(R.id.bAddHttpParam);
		tvHttpParameterExplanation = (TextView)findViewById(R.id.tvHttpParameterExplanation);

		etParameterName.setEnabled(false);
		etParameterValue.setEnabled(false);
		bAddHttpParam.setEnabled(false);

		rbTriggerUrlMethodPost.setOnCheckedChangeListener(new OnCheckedChangeListener()
		{
			@Override
			public void onCheckedChanged(CompoundButton compoundButton, boolean checked)
			{
				etParameterName.setEnabled(checked);
				etParameterValue.setEnabled(checked);
				bAddHttpParam.setEnabled(checked);
				if(checked)
					lvTriggerUrlPostParameters.setVisibility(View.VISIBLE);
			}
		});

		tvHttpParameterExplanation.setText(String.format(getResources().getString(R.string.httpParametersExplanation), Miscellaneous.httpMainData, Miscellaneous.doNoEncodingString));

		httpParametersAdapter = new ArrayAdapter<String>(this, R.layout.text_view_for_poi_listview_mediumtextsize, httpParamsList);

		bSaveTriggerUrl.setOnClickListener(new OnClickListener()
		{			
			@Override
			public void onClick(View v)
			{
				if(etTriggerUrl.getText().toString().length() > 0)
				{
					Intent returnIntent = new Intent();

					returnIntent.putExtra(ActivityManageRule.intentNameActionParameter1, chkTriggerUrlUseAuthentication.isChecked());

					String username = etTriggerUrlUsername.getText().toString();
					String password = etTriggerUrlPassword.getText().toString();

					if(username == null)
						username = "";

					if(password == null)
						password = "";

					String method = methodGet;
					if(rbTriggerUrlMethodPost.isChecked())
						method = methodPost;

					String httpParams = "";
					for (String s : httpParamsList)
						httpParams += Action.actionParameters2SeparatorOuter + s;
					if(httpParams.length() > 0)
						httpParams = httpParams.substring(Action.actionParameters2SeparatorOuter.length());

					returnIntent.putExtra(ActivityManageRule.intentNameActionParameter2,
																			username + Action.actionParameter2Split +
																			password + Action.actionParameter2Split +
																			etTriggerUrl.getText().toString().trim() + Action.actionParameter2Split +
																			method + Action.actionParameter2Split +
																			httpParams
																		);

					setResult(RESULT_OK, returnIntent);
					finish();
				}
				else
					Toast.makeText(getBaseContext(), getResources().getString(R.string.urlTooShort), Toast.LENGTH_LONG).show();
			}
		});

		chkTriggerUrlUseAuthentication.setOnCheckedChangeListener(new OnCheckedChangeListener()
		{
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
			{
				if(isChecked)
				{
					tlTriggerUrlAuthentication.setVisibility(View.VISIBLE);
					rbTriggerUrlMethodGet.setChecked(false);
					rbTriggerUrlMethodPost.setChecked(true);
					rbTriggerUrlMethodGet.setEnabled(false);
					rbTriggerUrlMethodPost.setEnabled(false);
				}
				else
				{
					tlTriggerUrlAuthentication.setVisibility(View.GONE);
					rbTriggerUrlMethodGet.setEnabled(true);
					rbTriggerUrlMethodPost.setEnabled(true);
				}

				etTriggerUrlUsername.setEnabled(isChecked);
				etTriggerUrlPassword.setEnabled(isChecked);
			}
		});
		
		lvTriggerUrlPostParameters.setOnItemLongClickListener(new OnItemLongClickListener()
		{
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
			{
				return false;
			}
		});
		updateListView();

		if(getIntent().hasExtra(ActivityManageRule.intentNameActionParameter2))
		{
			// username,password,URL,etc.
			String[] components;

			if(getIntent().getStringExtra(ActivityManageRule.intentNameActionParameter2).contains(Action.actionParameter2Split))
				components = getIntent().getStringExtra(ActivityManageRule.intentNameActionParameter2).split(Action.actionParameter2Split, -1);
			else
				components = getIntent().getStringExtra(ActivityManageRule.intentNameActionParameter2).split(";", -1);
			
			if(components.length >= 3)
			{
				etTriggerUrl.setText(components[2]);
				chkTriggerUrlUseAuthentication.setChecked(getIntent().getBooleanExtra(ActivityManageRule.intentNameActionParameter1, false));
				etTriggerUrlUsername.setText(components[0]);
				etTriggerUrlPassword.setText(components[1]);

				if(components.length >= 4)
				{
					switch(components[3])
					{
						case methodPost:
							rbTriggerUrlMethodPost.setChecked(true);
							break;
						case methodGet:
						default:
							rbTriggerUrlMethodGet.setChecked(true);
							break;
					}
				}

				if(components.length >= 5)
				{
					if(!StringUtils.isEmpty(components[4]) && components[4].contains(Action.actionParameters2SeparatorInner))
					{
						String httpParams[] = components[4].split(Action.actionParameters2SeparatorOuter);
						for (String paramPair : httpParams)
							httpParamsList.add(paramPair);

						updateHttpParamsList();
					}
				}
			}
			else
				etTriggerUrl.setText(components[0]);
		}

		bAddHttpParam.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View view)
			{
				if(StringUtils.isEmpty(etParameterName.getText()) || StringUtils.isEmpty(etParameterValue.getText()))
				{
					Toast.makeText(ActivityManageActionTriggerUrl.this, getResources().getString(R.string.enterValidDataIntoParametersFields), Toast.LENGTH_SHORT).show();
					return;
				}

				httpParamsList.add(etParameterName.getText() + Action.actionParameters2SeparatorInner + etParameterValue.getText());

				updateHttpParamsList();
				etParameterName.setText("");
				etParameterValue.setText("");

				if(lvTriggerUrlPostParameters.getVisibility() != View.VISIBLE)
					lvTriggerUrlPostParameters.setVisibility(View.VISIBLE);
			}
		});

		lvTriggerUrlPostParameters.setOnItemLongClickListener(new OnItemLongClickListener()
		{
			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
			{
				getHttpParamsDialog(arg2).show();
				return false;
			}
		});
	}

	private void updateListView()
	{
		Miscellaneous.logEvent("i", "ListView", "Attempting to update lvTriggerUrlPostParameters", 4);
		try
		{
			if(lvTriggerUrlPostParameters.getAdapter() == null)
				lvTriggerUrlPostParameters.setAdapter(lvTriggerUrlPostParametersAdapter);

			lvTriggerUrlPostParametersAdapter.notifyDataSetChanged();
		}
		catch(NullPointerException e)
		{}
	}

	private void updateHttpParamsList()
	{
		if(lvTriggerUrlPostParameters.getAdapter() == null)
			lvTriggerUrlPostParameters.setAdapter(httpParametersAdapter);

		httpParametersAdapter.notifyDataSetChanged();
	}

	private AlertDialog getHttpParamsDialog(final int itemPosition)
	{
		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(ActivityManageActionTriggerUrl.this);
		alertDialogBuilder.setTitle(getResources().getString(R.string.whatToDoWithIntentPair));
		alertDialogBuilder.setItems(new String[]{getResources().getString(R.string.delete)}, new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				// Only 1 choice at the moment, no need to check
				ActivityManageActionTriggerUrl.this.httpParamsList.remove(itemPosition);
				updateHttpParamsList();
			}
		});
		AlertDialog alertDialog = alertDialogBuilder.create();
		return alertDialog;
	}
}
