package com.handheld.apiinstructions;

import com.handheld.Barcode1DDemo.Barcode1DActivity;
import com.handheld.Barcode2DDemo.Barcode2DActivity;
import com.handheld.HFDemo.HFActivity;
import com.handheld.HFDemo.LegicActivity;
import com.handheld.HFDemo.NFCActivity;
import com.handheld.KeyTest.KeyTestActivity;
import com.handheld.LF125KDemo.LF125KActivity;
import com.handheld.LF134KDemo.LF134KActivity;
import com.handheld.SerialportTest.SerialportActivity;
import com.handheld.UHFDemo.UHFActivity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.pda.serialport.SerialPort;


import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;



public class MainActivity extends Activity {
	private static final int PERMISSIONS_REQUEST_CODE = 100;

	private int id = 1;
	int screenWidth;
	int screenHeight;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		screenWidth = getWindowManager().getDefaultDisplay().getWidth(); //
		screenHeight = getWindowManager().getDefaultDisplay().getHeight(); //

		initView();
	}

	private void initView() {
		LinearLayout newLayout = new LinearLayout(this);
		LinearLayout.LayoutParams LP_150 = new LinearLayout.LayoutParams(screenWidth/4,
				screenHeight/5);
		final LinearLayout lin = new LinearLayout(this);
		lin.setOrientation(LinearLayout.VERTICAL);
		final LinearLayout lin0 = new LinearLayout(this);
		lin0.setOrientation(LinearLayout.HORIZONTAL);
		lin0.setGravity(Gravity.LEFT);
		newLayout=generateSingleLayout3(R.drawable.reset,0,getString(R.string.reset));
		lin0.addView(newLayout,LP_150);
		newLayout=generateSingleLayout3(R.drawable.about,0,getString(R.string.about));
		lin0.addView(newLayout,LP_150);
		newLayout=generateSingleLayout3(R.drawable.help,0,getString(R.string.help));
		lin0.addView(newLayout,LP_150);
		newLayout=generateSingleLayout3(R.drawable.exit,0,getString(R.string.exit));
		lin0.addView(newLayout,LP_150);
		final LinearLayout lin1 = new LinearLayout(this);
		lin1.setOrientation(LinearLayout.HORIZONTAL);
		lin1.setGravity(Gravity.LEFT);
		final LinearLayout lin2 = new LinearLayout(this);
		lin2.setOrientation(LinearLayout.HORIZONTAL);
		lin2.setGravity(Gravity.LEFT);
		final LinearLayout lin3 = new LinearLayout(this);
		lin3.setOrientation(LinearLayout.HORIZONTAL);
		lin3.setGravity(Gravity.LEFT);
		
		sharedPreferences = this.getSharedPreferences("serialport", MODE_PRIVATE);
		editor = sharedPreferences.edit();
		boolean isFirstRun = sharedPreferences.getBoolean("isFirstRun", true);
		if (isFirstRun) {
			Selectconfigs();
		}
		boolean is1d = sharedPreferences.getBoolean("1d", false);
		if (is1d) {
			newLayout = generateSingleLayout3(R.drawable.scan1d, id++,
					getString(R.string._1d));
			lin1.addView(newLayout, LP_150);
		}
		boolean is2d = sharedPreferences.getBoolean("2d", false);
		if (is2d) {
			newLayout = generateSingleLayout3(R.drawable.scan2d, id++,
					getString(R.string._2d));
			lin1.addView(newLayout, LP_150);
		}
		boolean ishf14443a = sharedPreferences.getBoolean("hf14443a", false);
		if (ishf14443a) {
			newLayout = generateSingleLayout3(R.drawable.hf, id++,
					getString(R.string.hf_n14443a));
			lin1.addView(newLayout, LP_150);
		}
		boolean ishf15693 = sharedPreferences.getBoolean("hf15693", false);
		if (ishf15693) {
			newLayout = generateSingleLayout3(R.drawable.hf, id++,
					getString(R.string.hf_n15693));
			lin1.addView(newLayout, LP_150);
		}
		boolean isLegic = sharedPreferences.getBoolean("legic", false);
		if (isLegic) {
			if (id <= 4) {
				newLayout = generateSingleLayout3(R.drawable.legic, id++, "Legic");
				lin1.addView(newLayout, LP_150);
			} else if (id <= 8) {
				newLayout = generateSingleLayout3(R.drawable.legic, id++, "Legic");
				lin2.addView(newLayout, LP_150);
			}
		}
		boolean isuhf = sharedPreferences.getBoolean("uhf", false);
		if (isuhf) {
			if (id<=4) {
				newLayout = generateSingleLayout3(R.drawable.uhf_launcher, id++,
						getString(R.string.uhf));
				lin1.addView(newLayout, LP_150);
			}else if (id>4&&id<=8) {
				newLayout = generateSingleLayout3(R.drawable.uhf_launcher, id++,
						getString(R.string.uhf));
				lin2.addView(newLayout, LP_150);
			}
		}
		boolean isnfc = sharedPreferences.getBoolean("nfc", false);
		if (isnfc) {
			if (id<=4) {
				newLayout = generateSingleLayout3(R.drawable.nfc, id++,
						"NFC");
				lin1.addView(newLayout, LP_150);
			}else if (id>4&&id<=8) {
				newLayout = generateSingleLayout3(R.drawable.nfc, id++,
						"NFC");
				lin2.addView(newLayout, LP_150);
			}
		}
		
		boolean islf134 = sharedPreferences.getBoolean("lf134", false);
		if (islf134) {
			if (id<=4) {
				newLayout = generateSingleLayout3(R.drawable.lf, id++,
						getString(R.string.lf_134_));
				lin1.addView(newLayout, LP_150);
			}else if (id>4&&id<=8) {
				newLayout = generateSingleLayout3(R.drawable.lf, id++,
						getString(R.string.lf_134_));
				lin2.addView(newLayout, LP_150);
			}else if (id>8) {
				newLayout = generateSingleLayout3(R.drawable.lf, id++,
						getString(R.string.lf_134_));
				lin3.addView(newLayout, LP_150);
			}
		}
		boolean islf125 = sharedPreferences.getBoolean("lf125", false);
		if (islf125) {
			if (id<=4) {
				newLayout = generateSingleLayout3(R.drawable.lf, id++,
						getString(R.string.lf_125_));
				lin1.addView(newLayout, LP_150);
			}else if (id>4&&id<=8) {
				newLayout = generateSingleLayout3(R.drawable.lf, id++,
						getString(R.string.lf_125_));
				lin2.addView(newLayout, LP_150);
			}else if (id>8) {
				newLayout = generateSingleLayout3(R.drawable.lf, id++,
						getString(R.string.lf_125_));
				lin3.addView(newLayout, LP_150);
			}
		}
		boolean isserialport = sharedPreferences
				.getBoolean("serialport", false);
		if (isserialport) {
			if (id<=4) {
				newLayout = generateSingleLayout3(R.drawable.serialport, id++,
						getString(R.string.serialport_debugging_tool));
				lin1.addView(newLayout, LP_150);
			}else if (id>4&&id<=8) {
				newLayout = generateSingleLayout3(R.drawable.serialport, id++,
						getString(R.string.serialport_debugging_tool));
				lin2.addView(newLayout, LP_150);
			}else if (id>8) {
				newLayout = generateSingleLayout3(R.drawable.serialport, id++,
						getString(R.string.serialport_debugging_tool));
				lin3.addView(newLayout, LP_150);
			}
		}
		boolean keytest = sharedPreferences.getBoolean("keytest", false);
		if (keytest) {
			if (id<=4) {
				newLayout = generateSingleLayout3(R.drawable.key, id++,
						getString(R.string.keytest));
				lin1.addView(newLayout, LP_150);
			}else if (id>4&&id<=8) {
				newLayout = generateSingleLayout3(R.drawable.key, id++,
						getString(R.string.keytest));
				lin2.addView(newLayout, LP_150);
			}else if (id>8) {
				newLayout = generateSingleLayout3(R.drawable.key, id++,
						getString(R.string.keytest));
				lin3.addView(newLayout, LP_150);
			}
		}
		lin.addView(lin0);
		lin.addView(lin1);
		if (id>4) {
			lin.addView(lin2);
		}
		if (id>8) {
			lin.addView(lin3);
		}
		setContentView(lin);

		// Check and request permissions
		requestPermissionsOnStartup();
	}

	private void requestPermissionsOnStartup() {
		// Check each permission and request if not granted
		if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
				ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
				ContextCompat.checkSelfPermission(this, Manifest.permission.NFC) != PackageManager.PERMISSION_GRANTED) {

			ActivityCompat.requestPermissions(this,
					new String[]{
							Manifest.permission.WRITE_EXTERNAL_STORAGE,
							Manifest.permission.READ_EXTERNAL_STORAGE,
							Manifest.permission.NFC
					},
					PERMISSIONS_REQUEST_CODE);
		} else {
			// All permissions already granted
			Toast.makeText(this, "All permissions granted!", Toast.LENGTH_SHORT).show();
		}
	}

	private LinearLayout generateSingleLayout3(final int image,
			final int imageID, final String str) {
		LinearLayout layout_sub_Lin = new LinearLayout(this);
		LinearLayout.LayoutParams linParams = new LinearLayout.LayoutParams(
				150, 150);
		layout_sub_Lin.setLayoutParams(linParams);
		layout_sub_Lin.setOrientation(LinearLayout.VERTICAL);
		layout_sub_Lin.setGravity(Gravity.CENTER_HORIZONTAL);
		layout_sub_Lin.setPadding(5, 5, 5, 5);

		ImageView imageView = new ImageView(this);
		RelativeLayout.LayoutParams RL_WW = new RelativeLayout.LayoutParams(
				100, 100);
		imageView.setPadding(0, 0, 0, 0);
		imageView.setLayoutParams(RL_WW);
		imageView.setClickable(true);
		imageView.setId(imageID);
		imageView.setImageResource(image);
		layout_sub_Lin.addView(imageView);

		imageView.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if (image == R.drawable.scan1d) {
					Intent intent_scan = new Intent(MainActivity.this,
							Barcode1DActivity.class);
					MainActivity.this.startActivity(intent_scan);
				} else if (image == R.drawable.scan2d){
						Intent intent_scan2d = new Intent(MainActivity.this,
								Barcode2DActivity.class);
					MainActivity.this.startActivity(intent_scan2d);
				} else if (image == R.drawable.hf) {
					if (str.equals(getString(R.string.hf_n14443a))) {
						Intent intent_hf14443a = new Intent(MainActivity.this,
								HFActivity.class);
						intent_hf14443a.putExtra("14443a", true);
						MainActivity.this.startActivity(intent_hf14443a);
					} else {
						Intent intent_hf15693 = new Intent(MainActivity.this,
								HFActivity.class);
						intent_hf15693.putExtra("14443a", false);
						MainActivity.this.startActivity(intent_hf15693);
					}
				} else if (image == R.drawable.legic) {
					Intent intent_legic = new Intent(MainActivity.this,
							LegicActivity.class);
					MainActivity.this.startActivity(intent_legic);
				} else if (image == R.drawable.nfc) {
					Intent intent_nfc = new Intent(MainActivity.this,
							NFCActivity.class);
					MainActivity.this.startActivity(intent_nfc);
				} else if (image == R.drawable.uhf_launcher) {
					if (str.equals(getString(R.string.uhf))) {
						Intent intent_uhf = new Intent(MainActivity.this,
								UHFActivity.class);
						MainActivity.this.startActivity(intent_uhf);
					}
				} else if (image == R.drawable.ic_launcher) {

				} else if (image == R.drawable.lf) {
					if (str.equals(getString(R.string.lf_125_))) {
						Intent intent_lf125 = new Intent(MainActivity.this,
								LF125KActivity.class);
						MainActivity.this.startActivity(intent_lf125);
					} else {
						Intent intent_lf134 = new Intent(MainActivity.this,
								LF134KActivity.class);
						MainActivity.this.startActivity(intent_lf134);
					}
				} else if (image == R.drawable.serialport) {
					Intent intent_serialport = new Intent(MainActivity.this,
							SerialportActivity.class);
					MainActivity.this.startActivity(intent_serialport);
				} else if (image == R.drawable.key) {
					Intent intent_keytest = new Intent(MainActivity.this,
							KeyTestActivity.class);
					MainActivity.this.startActivity(intent_keytest);
				} else if (image == R.drawable.reset) {
					reset();
				} else if (image == R.drawable.about) {

				} else if (image == R.drawable.help) {

				} else if (image == R.drawable.exit) {
					finish();
				}
			}
		});

		TextView tv = new TextView(this);
		LinearLayout.LayoutParams LP_WW = new LinearLayout.LayoutParams(150,
				150);
		tv.setText(str);
		tv.setTextColor(Color.argb(0xff, 0x00, 0x00, 0x00));
		tv.setTextSize(screenHeight/64);
		tv.setGravity(Gravity.CENTER_HORIZONTAL);
		tv.setLayoutParams(LP_WW);
		layout_sub_Lin.addView(tv);
		return layout_sub_Lin;
	}

	
	long exitSytemTime = 0;

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			if (System.currentTimeMillis() - exitSytemTime > 2000) {
				Toast.makeText(getApplicationContext(), R.string.exitSystem,
						Toast.LENGTH_SHORT).show();
				exitSytemTime = System.currentTimeMillis();
				return true;
			} else {
				finish();
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	private void reset() {
		AlertDialog dlg = new AlertDialog.Builder(MainActivity.this)
				.setTitle(R.string.are_you_sure_to_reset_)
				.setPositiveButton(R.string.sure,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
								editor.putInt("barcodeport", SerialPort.com0);
								editor.putInt("barcodebaudrate",
										SerialPort.baudrate9600);
								editor.putInt("barcodepower",
										SerialPort.Power_Scaner);
								editor.putInt("hfport", SerialPort.com14);
								editor.putInt("hfbaudrate",
										SerialPort.baudrate115200);
								editor.putInt("hfpower", SerialPort.Power_Psam);

								editor.putInt("lfhdx125port", SerialPort.com14);
								editor.putInt("lfhdx125baudrate",
										SerialPort.baudrate9600);
								editor.putInt("lfhdx125power",
										SerialPort.Power_Psam);

								editor.putInt("nfcport", SerialPort.com14);
								editor.putInt("nfcbaudrate",
										SerialPort.baudrate9600);
								editor.putInt("nfcpower", SerialPort.Power_Psam);

								editor.putInt("uhfport", SerialPort.com13);
								editor.putInt("uhfbaudrate",
										SerialPort.baudrate115200);
								editor.putInt("uhfpower", SerialPort.Power_Rfid);

								editor.putInt("uhflport", SerialPort.com12);
								editor.putInt("uhflbaudrate",
										SerialPort.baudrate115200);
								editor.putInt("uhflpower", SerialPort.Power_5v);
								editor.putBoolean("isFirstRun", true);
								editor.putBoolean("1d", false);
								editor.putBoolean("2d", false);
								editor.putBoolean("hf14443a", false);
								editor.putBoolean("hf15693", false);
								editor.putBoolean("legic", false);
								editor.putBoolean("uhf", false);
								editor.putBoolean("nfc", false);
								editor.putBoolean("lf134", false);
								editor.putBoolean("lf125", false);
								editor.putBoolean("serialport",false);
								editor.putBoolean("keytest", false);
								editor.commit();
								Toast.makeText(MainActivity.this,
										"Reset success!", Toast.LENGTH_SHORT)
										.show();
								Intent intent = new Intent(MainActivity.this,MainActivity.class);
								finish();
								MainActivity.this.startActivity(intent);
							}
						})
				.setNegativeButton(R.string.cancel,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int whichButton) {
							}
						}).create();
		dlg.show();

	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.mainactivity, menu);
		return true;
	}

	// go to
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.action_configs) {
			Selectconfigs();
		}
		return super.onOptionsItemSelected(item);
	}

	private SharedPreferences sharedPreferences;
	private Editor editor;
	private String[] configs;
	private int[] configs_int;
	private int[] configs_select_int;
	private boolean[] configs_boolean;
	private ListView configsListView = null;

	private void Selectconfigs() {
		configs = new String[] { getResources().getString(R.string._1d),
				getResources().getString(R.string._2d),
				getResources().getString(R.string.hf_iso14443a),
				getResources().getString(R.string.hf_iso15693),
				"NFC",
				"Legic",
				getResources().getString(R.string.uhf),
				getResources().getString(R.string.lf_134_),
				getResources().getString(R.string.lf_125_),
				getResources().getString(R.string.serialport_debugging_tool),
				getResources().getString(R.string.keytest)};
		configs_int = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11};
		configs_boolean = new boolean[] { false, false, false, false, false,
				false, false, false, false, false, false};
		AlertDialog ad = new AlertDialog.Builder(MainActivity.this)
				.setTitle(R.string.select_configs_)
				.setMultiChoiceItems(configs, configs_boolean,
						new DialogInterface.OnMultiChoiceClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int whichButton, boolean isChecked) {
							}
						})
				.setPositiveButton(R.string.sure,
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int whichButton) {
								configs_select_int = null;
								for (int i = 0; i < configs_int.length; i++) {
									if (configsListView
											.getCheckedItemPositions().get(i)) {
										if (configs_select_int == null) {
											configs_select_int = new int[1];
											configs_select_int[0] = configs_int[i];
										} else {
											int[] newselect = new int[configs_select_int.length + 1];
											System.arraycopy(
													configs_select_int, 0,
													newselect, 0,
													configs_select_int.length);
											newselect[newselect.length - 1] = configs_int[i];
											configs_select_int = newselect;
										}
									} else {
										configsListView
												.getCheckedItemPositions().get(
														i, false);
									}
								}
								if (configs_select_int != null) {
									editor.putBoolean("isFirstRun", false);
									editor.commit();
									for (int i = 0; i < configs_select_int.length; i++) {
										switch (configs_select_int[i]) {
										case 1:
											editor.putBoolean("1d", true);
											break;
										case 2:
											editor.putBoolean("2d", true);
											break;
										case 3:
											editor.putBoolean("hf14443a", true);
											break;
										case 4:
											editor.putBoolean("hf15693", true);
											break;
										case 5:
											editor.putBoolean("nfc", true);
											break;
										case 6:
											editor.putBoolean("legic", true);
											break;
										case 7:
											editor.putBoolean("uhf", true);
											break;
										case 8:
											editor.putBoolean("lf134", true);
											break;
										case 9:
											editor.putBoolean("lf125", true);
											break;
										case 10:
											editor.putBoolean("serialport", true);
											break;
										case 11:
											editor.putBoolean("keytest", true);
											break;

										default:
											break;
										}
									}
								}
								editor.commit();
								finish();
								Intent intent = new Intent(MainActivity.this,MainActivity.class);
								MainActivity.this.startActivity(intent);
							}
						}).setNegativeButton(R.string.cancle, null).create();
		configsListView = ad.getListView();
		ad.show();
	}
}
