package com.jens.automation2;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.text.method.LinkMovementMethod;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class ActivityManageActionSetSystemSetting extends Activity
{
    Spinner spinnerSettingTarget, spinnerSettingDataType;
	EditText etSettingName, etSettingValue;
    Button bSaveSetSystemSetting;
    TextView tvSetSystemSettingExamples, tvSetSystemSettingNoticeWriteSecureSettings;

    ArrayAdapter<String> settingTargetSpinnerAdapter, settingDataTypeSpinnerAdapter;
    protected final static String[] targets = { "Global", "System", "Secure" };
    protected final static String[] dataTypes = { "String", "Long", "Int", "Float" };
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		Miscellaneous.setDisplayLanguage(this);
		Miscellaneous.setUiTheme(this);
		this.setContentView(R.layout.activity_manage_action_set_system_setting);

        spinnerSettingTarget = (Spinner) findViewById(R.id.spinnerSettingTarget);
        spinnerSettingDataType = (Spinner) findViewById(R.id.spinnerSettingDataType);
        etSettingName = (EditText)findViewById(R.id.etSettingName);
        etSettingValue = (EditText)findViewById(R.id.etSettingValue);
        bSaveSetSystemSetting = (Button)findViewById(R.id.bSaveSetSystemSetting);
        tvSetSystemSettingExamples = (TextView)findViewById(R.id.tvSetSystemSettingExamples);
        tvSetSystemSettingNoticeWriteSecureSettings = (TextView)findViewById(R.id.tvSetSystemSettingNoticeWriteSecureSettings);

        settingTargetSpinnerAdapter = new ArrayAdapter<String>(this, R.layout.text_view_for_poi_listview_mediumtextsize, targets);
        spinnerSettingTarget.setAdapter(settingTargetSpinnerAdapter);
        settingTargetSpinnerAdapter.notifyDataSetChanged();

        settingDataTypeSpinnerAdapter = new ArrayAdapter<String>(this, R.layout.text_view_for_poi_listview_mediumtextsize, dataTypes);
        spinnerSettingDataType.setAdapter(settingDataTypeSpinnerAdapter);
        settingDataTypeSpinnerAdapter.notifyDataSetChanged();

        tvSetSystemSettingExamples.setMovementMethod(LinkMovementMethod.getInstance());

        if(ActivityPermissions.havePermission(Manifest.permission.WRITE_SECURE_SETTINGS, ActivityManageActionSetSystemSetting.this))
            tvSetSystemSettingNoticeWriteSecureSettings.setVisibility(View.GONE);
        else
            tvSetSystemSettingNoticeWriteSecureSettings.setVisibility(View.VISIBLE);

        // Make links clickable
        tvSetSystemSettingNoticeWriteSecureSettings.setMovementMethod(LinkMovementMethod.getInstance());

        spinnerSettingDataType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
        {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l)
            {
                if(dataTypes[i].equalsIgnoreCase("String"))
                    etSettingValue.setInputType(InputType.TYPE_CLASS_TEXT);
                else if(dataTypes[i].equalsIgnoreCase("Float"))
                    etSettingValue.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
                else
                    etSettingValue.setInputType(InputType.TYPE_CLASS_NUMBER);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView)
            {

            }
        });

        bSaveSetSystemSetting.setOnClickListener(new OnClickListener()
		{			
			@Override
			public void onClick(View v)
			{
                if(etSettingName.getText().toString().isEmpty())
                {
                    Toast.makeText(getBaseContext(), getResources().getString(R.string.enterAname), Toast.LENGTH_LONG).show();
                    return;
                }

                if(etSettingValue.getText().toString().isEmpty())
                {
                    Toast.makeText(getBaseContext(), getResources().getString(R.string.enterAvalue), Toast.LENGTH_LONG).show();
                    return;
                }
                else
                {
                    String selectedDataType = dataTypes[spinnerSettingDataType.getSelectedItemPosition()];
                    if(
                            selectedDataType.equalsIgnoreCase("Int")
                                ||
                            selectedDataType.equalsIgnoreCase("Long")
                    )
                    {
                        if(!Miscellaneous.isNumeric(etSettingValue.getText().toString()) || !Miscellaneous.isNumericNonDecimal(etSettingValue.getText().toString()))
                        {
                            Toast.makeText(ActivityManageActionSetSystemSetting.this, getResources().getString(R.string.enter_a_number), Toast.LENGTH_LONG).show();
                            return;
                        }
                    }
                    else if(selectedDataType.equalsIgnoreCase("Float"))
                    {
                        if(!Miscellaneous.isNumeric(etSettingValue.getText().toString()))
                        {
                            Toast.makeText(ActivityManageActionSetSystemSetting.this, getResources().getString(R.string.enter_a_number), Toast.LENGTH_LONG).show();
                            return;
                        }
                    }
                }

                Intent returnIntent = new Intent();

                String param2Data = targets[spinnerSettingTarget.getSelectedItemPosition()] + Action.actionParameter2Split + dataTypes[spinnerSettingDataType.getSelectedItemPosition()] + Action.actionParameter2Split + etSettingName.getText().toString() + Action.actionParameter2Split + etSettingValue.getText().toString();

                returnIntent.putExtra(ActivityManageRule.intentNameActionParameter1, false);
                returnIntent.putExtra(ActivityManageRule.intentNameActionParameter2, param2Data);

                setResult(RESULT_OK, returnIntent);
                finish();
			}
		});

        if(getIntent().hasExtra(ActivityManageRule.intentNameActionParameter2))
		{
			// dataType, setting name, setting value
			String[] components = getIntent().getStringExtra(ActivityManageRule.intentNameActionParameter2).split(Action.actionParameter2Split, -1);

            if(components.length == 4)
            {
                int positionTarget = Miscellaneous.arraySearchIndexOf(targets, components[0], false, true);
                int positionDataType = Miscellaneous.arraySearchIndexOf(dataTypes, components[1], false, true);

                if(positionDataType >= 0)
                {
                    spinnerSettingTarget.setSelection(positionTarget);
                    spinnerSettingDataType.setSelection(positionDataType);
                    etSettingName.setText(components[2]);
                    etSettingValue.setText(components[3]);
                }
            }
            else
            {
                int position = Miscellaneous.arraySearchIndexOf(dataTypes, components[0], false, true);

                if (position >= 0)
                {
                    spinnerSettingDataType.setSelection(position);
                    etSettingName.setText(components[1]);
                    etSettingValue.setText(components[2]);
                }
            }
		}
	}

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

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