package kz.istt.locust;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.URLUtil;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.text.TextWatcher;
import android.widget.Toast;

import com.google.android.gms.vision.Frame;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;

import java.util.Locale;

import dbfields.InputFilterMinMax;


public class SetupActivity extends Activity {

	//Для смены языка на лету
	//private Locale myLocale;
    private SharedPreferences preferences;
    private Locale locale;
    private String lang;
    //private OrientationEventListener mOrientationListener=null;

	//public ProgressDialog dialog;
	//public Handler myHandle;
  
	public Button btnSynchronization = null; //Кнопка синхронизации
	public TextView tvSynchronization = null; //
	public Button btnDr = null;
	public Button btnAz = null;
	public Button btnEn = null;
	public Button btnGr = null;
	public Button btnKg = null;
	public Button btnKz = null;
	public Button btnRu = null;
	public Button btnUz = null;
	public Button btnTj = null;
	public Button btnTm = null;
	public Button btnAr = null;
	public Button btnQR = null;
	public Button btnDeleteAllData = null;
	public EditText edtURL = null;
	public EditText edtSyncDays = null;
	public CheckBox cbIdentifyCountryRegion = null;
	public CheckBox cbOrderByDistance = null;

	public CheckBox cbShowAdvancedSettings = null;

	public final static int TASK1_CODE = 1;
	public final static int TASK2_CODE = 2;
	public final static int TASK3_CODE = 3;
	public final static int STATUS_START = 100;
	public final static int STATUS_FINISH = 200;
	//public final static String PARAM_ACTION = "ACTION";
	public final static String PARAM_PINTENT = "pendingIntent";
	public final static String PARAM_RESULT = "result";


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_setup);
		
/*
		mOrientationListener = new OrientationEventListener(this,
		            SensorManager.SENSOR_DELAY_NORMAL) {

		            @Override
		            public void onOrientationChanged(int orientation)
		            {
		            	Log.e("CCALM", "Orientation changed to " + orientation);
		            }
		        };
		        
		        
		        if (mOrientationListener.canDetectOrientation() == true) {
		            Log.e("CCALM", "Can detect orientation");
		            mOrientationListener.enable();
		        } else {
		            Log.e("CCALM", "Cannot detect orientation");
		            mOrientationListener.disable();
		        }
*/
		
		//Загрузка сохранёного языка
		Tools.loadLocale(this);

		//Прячу всё что должно быть спрятано
		((LinearLayout)findViewById(R.id.llShowAdvancedSettings)).setVisibility(View.GONE);

		tvSynchronization = (TextView)findViewById(R.id.tvSynchronization);

		//Кнопочка синхронизировать
		btnSynchronization = (Button) findViewById(R.id.btnSynchronization);
		OnClickListener oclBtnSynchronization = new OnClickListener()
		{
			 @Override
			public void onClick(View v)
			{
				startService(new Intent(SetupActivity.this, MainService.class).putExtra(MainService.PARAM_ACTION, "1")); // Чтоб вызвать событие таймера в сервисе
			}
		};
		btnSynchronization.setOnClickListener(oclBtnSynchronization);

		//Выбор языка
		btnDr = (Button) findViewById(R.id.btnDr);
		OnClickListener oclbtnDr = new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Tools.saveLocale(SetupActivity.this, "ps");
				updateTexts();
			}
		};
		btnDr.setOnClickListener(oclbtnDr);
		
		//Выбор языка
		btnAz = (Button) findViewById(R.id.btnAz);
		OnClickListener oclBtnAz = new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Tools.saveLocale(SetupActivity.this, "az");
				updateTexts();
			}
		};
		btnAz.setOnClickListener(oclBtnAz);

		//Выбор англйского языка
		btnEn = (Button) findViewById(R.id.btnEn);
		OnClickListener oclBtnEn = new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Tools.saveLocale(SetupActivity.this, "en");
				updateTexts();
			}
		};
		btnEn.setOnClickListener(oclBtnEn);
		
		//Выбор Грузинского языка
		btnGr = (Button) findViewById(R.id.btnGr);
		OnClickListener oclBtnGr = new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Tools.saveLocale(SetupActivity.this, "ka");
				updateTexts();
			}
		};
		btnGr.setOnClickListener(oclBtnGr);

		//Кыргыз
		btnKg = (Button) findViewById(R.id.btnKg);
		OnClickListener oclBtnKg = new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Tools.saveLocale(SetupActivity.this, "kg");
				updateTexts();
			}
		};
		btnKg.setOnClickListener(oclBtnKg);
		
		//Выбор Казахского языка
		btnKz = (Button) findViewById(R.id.btnKz);
		OnClickListener oclBtnKz = new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{

				Tools.saveLocale(SetupActivity.this, "kk");
				updateTexts();
			}
		};
		btnKz.setOnClickListener(oclBtnKz);
		
		
		//Выбор руского языка
		btnRu = (Button) findViewById(R.id.btnRu);
		OnClickListener oclBtnRu = new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Tools.saveLocale(SetupActivity.this, "ru");
				updateTexts();
			}
		};
		btnRu.setOnClickListener(oclBtnRu);

		//Выбор узбекского языка
		btnUz = (Button) findViewById(R.id.btnUz);
		OnClickListener oclBtnUz = new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Tools.saveLocale(SetupActivity.this, "uz");
				updateTexts();
			}
		};
		btnUz.setOnClickListener(oclBtnUz);
		
		//Выбор Таджикского языка
		btnTj = (Button) findViewById(R.id.btnTj);
		OnClickListener oclBtnTj = new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Tools.saveLocale(SetupActivity.this, "tg");
				updateTexts();
			}
		};
		btnTj.setOnClickListener(oclBtnTj);

		//Выбор Туркменского языка
		btnTm = (Button) findViewById(R.id.btnTm);
		OnClickListener oclBtnTm = new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Tools.saveLocale(SetupActivity.this, "tk");
				updateTexts();
			}
		};
		btnTm.setOnClickListener(oclBtnTm);

		//Выбор Армянского языка
		btnAr = (Button) findViewById(R.id.btnAr);
		OnClickListener oclBtnAr = new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				Tools.saveLocale(SetupActivity.this, "hy");
				updateTexts();
			}
		};
		btnAr.setOnClickListener(oclBtnAr);


		cbIdentifyCountryRegion = (CheckBox) findViewById(R.id.cbIdentifyCountryRegion);

		String prefName = "Identify";
		SharedPreferences prefs = getSharedPreferences("CommonPrefs", Activity.MODE_PRIVATE);
		String checked = prefs.getString(prefName, "");
		if(checked.equals("") || checked.equals("1"))
			cbIdentifyCountryRegion.setChecked(true);
		else
			cbIdentifyCountryRegion.setChecked(false);

		OnClickListener oclBtnId = new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				String prefName = "Identify";
				SharedPreferences prefs = getSharedPreferences("CommonPrefs", Activity.MODE_PRIVATE);
				SharedPreferences.Editor editor = prefs.edit();
				if(cbIdentifyCountryRegion.isChecked())
					editor.putString(prefName, "1"); //Default value
				else
					editor.putString(prefName, "0");
				editor.apply();
			}
		};
		cbIdentifyCountryRegion.setOnClickListener(oclBtnId);



		cbOrderByDistance = (CheckBox) findViewById(R.id.cbOrderByDistance);

		prefName = "Distance";
		prefs = getSharedPreferences("CommonPrefs", Activity.MODE_PRIVATE);
		checked = prefs.getString(prefName, "");
		if(checked.equals("") || checked.equals("1"))
			cbOrderByDistance.setChecked(true);
		else
			cbOrderByDistance.setChecked(false);

		oclBtnId = new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				String prefName = "Distance";
				SharedPreferences prefs = getSharedPreferences("CommonPrefs", Activity.MODE_PRIVATE);
				SharedPreferences.Editor editor = prefs.edit();
				if(cbOrderByDistance.isChecked())
					editor.putString(prefName, "1"); //Default value
				else
					editor.putString(prefName, "0");
				editor.apply();
			}
		};
		cbOrderByDistance.setOnClickListener(oclBtnId);

		//Кнопка для сканирования QR кода
		btnQR = (Button) findViewById(R.id.btnQR);
		OnClickListener oclBtnQR = new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				startActivity(new Intent(SetupActivity.this, ScanActivity.class));
			}
		};
		btnQR.setOnClickListener(oclBtnQR);


		OnClickListener oclShowAdvancedSettings = new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if(cbShowAdvancedSettings.isChecked())
					((LinearLayout)findViewById(R.id.llShowAdvancedSettings)).setVisibility(View.VISIBLE);
				else
					((LinearLayout)findViewById(R.id.llShowAdvancedSettings)).setVisibility(View.GONE);
			}
		};
		cbShowAdvancedSettings = (CheckBox) findViewById(R.id.cbShowAdvancedSettings);
		cbShowAdvancedSettings.setOnClickListener(oclShowAdvancedSettings);

		edtURL = (EditText) findViewById(R.id.edtURL);
		edtURL.setText(MySynchronizationOld.URL);

		edtURL.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
			@Override
			public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
			@Override
			public void afterTextChanged(Editable editable) {
				if (URLUtil.isValidUrl(editable.toString())) {
					SharedPreferences prefs = SetupActivity.this.getSharedPreferences("CommonPrefs", Activity.MODE_PRIVATE);
					SharedPreferences.Editor editor = prefs.edit();
					editor.putString("URL", editable.toString());
					editor.apply(); // or editor.commit(); if you want to save synchronously
					MySynchronizationOld.URL = editable.toString();
				} else {
					Toast.makeText(SetupActivity.this, "Invalid URL", Toast.LENGTH_SHORT).show();
				}
			}
		});

		edtSyncDays = (EditText) findViewById(R.id.edtSyncDays);
		edtSyncDays.setFilters(new InputFilter[]{ new InputFilterMinMax(1, 365) });
		edtSyncDays.setText(String.valueOf(MySynchronizationOld.SyncDays));

		edtSyncDays.addTextChangedListener(new TextWatcher() {
			@Override
			public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
			@Override
			public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {}
			@Override
			public void afterTextChanged(Editable editable) {
				try {
					MySynchronizationOld.SyncDays=Integer.parseInt(edtSyncDays.getText().toString());
					SharedPreferences prefs = SetupActivity.this.getSharedPreferences("CommonPrefs", Activity.MODE_PRIVATE);
					SharedPreferences.Editor editor = prefs.edit();
					editor.putInt("SyncDays", MySynchronizationOld.SyncDays);
					editor.apply(); // or editor.commit(); if you want to save synchronously
				} catch (NumberFormatException e) {
					Toast.makeText(SetupActivity.this, "Invalid integer", Toast.LENGTH_SHORT).show();
				}
			}
		});

		//Button delete all data
		OnClickListener oclDeleteAllData = new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				AlertDialog.Builder adb = new AlertDialog.Builder(SetupActivity.this, R.style.AlertDialogTheme);
				adb.setTitle(getString(R.string.Warning));
				adb.setMessage(SetupActivity.this.getResources().getString(R.string.Do_you_really_want_to_delete_all_data_from_the_app));
				adb.setPositiveButton(SetupActivity.this.getResources().getString(R.string.Yes), new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int id) {
						//Delete all data
						DbOpenHelper dboh = new DbOpenHelper(SetupActivity.this);
						SQLiteDatabase wdb = null;
						try {
							wdb = dboh.getWritableDatabase();
							dboh.dropAllTables(wdb);
							dboh.onCreate(wdb);
						}catch(Exception e){
							e.printStackTrace();
						}finally{
							if(wdb!=null){ wdb.close(); }
						}
						dboh.close();

						//Restarting APP
						Intent intent = new Intent(SetupActivity.this, MainActivity.class);
						intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
						intent.putExtra("EXIT", true);
						startActivity(intent);
						finish();
					}
				});
				adb.setNegativeButton(SetupActivity.this.getResources().getString(R.string.No), new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {

					}
				});
				AlertDialog ad = adb.show();
				ad.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
				ad.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK);
			}
		};
		btnDeleteAllData = (Button) findViewById(R.id.btnDeleteAllData);
		btnDeleteAllData.setOnClickListener(oclDeleteAllData);

		//1 диалог на всё
		/*dialog = new ProgressDialog(SetupActivity.this);
		dialog.setMessage("Синхронизация...");
		dialog.setIndeterminate(true);
		dialog.setCancelable(true);*/
	}

	/** СМ. http://developer.android.com/reference/android/app/Activity.html
	 * Происходит при старте и при возврате на этот Activity
	 * */
	@Override
	public void onStart()
	{
		super.onStart();
		//Для возможности синхронизации прогресс бара передаём ниточку в поток
		PendingIntent pi = createPendingResult(TASK1_CODE, new Intent(this, MainService.class), 0);
		Intent intent = new Intent(this, MainService.class);
		intent.putExtra(MainService.PARAM_ACTION, "2");
		intent.putExtra(PARAM_PINTENT, pi);
		startService(intent);
	}

	@Override
	protected void onStop() {
		super.onStop();
/*
		//Удаляем слушателя
		Intent intent = new Intent(this, MainService.class);
		intent.putExtra(MainService.PARAM_ACTION, "3");
		startService(intent);
*/
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	    //mOrientationListener.disable();
	}
	
	@Override
	public void onConfigurationChanged(Configuration newConfig)
	{
		super.onConfigurationChanged(newConfig);
		
		/*locale = new Locale(lang);
		Locale.setDefault(locale);
		Configuration config = new Configuration();
		config.locale = locale;
		getBaseContext().getResources().updateConfiguration(config, null);*/
		
		//updateTexts();
	}
	
	/*@Override
    public void onOrientationChanged(int arg0) 
	{

    }*/

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		getMenuInflater().inflate(R.menu.setup, menu);
		return true;
	}

	//Обновление UI элементов текущего окна (обновлять необходимо только окно, в котором происходит смена локали):
	private void updateTexts()
	{
		Intent intent = getIntent();
		finish();
		startActivity(intent);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		//Пришли данные о статусе синхронизации
		if (resultCode == STATUS_FINISH)
		{
			int cnt = data.getIntExtra(PARAM_RESULT, 0);
			tvSynchronization.setText("Synchronization tasks: "+ String.valueOf(cnt));
		}
	}
}
