package com.lloydm.geosword.activities;

import java.util.Random;

import com.lloydm.geosword1.R;
import com.lloydm.geosword.common.Config;
import com.lloydm.geosword.common.UploadCompleteBroadcastReceiver;
import com.lloydm.geosword.common.UploadService;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class AuthenticateDialog
{
     private final static String TAG = "com.lloydm.geosword.activities.AuthenticateActivity";
     private EditText[] inputtxt;
     private Button[] btnaccount;

     private volatile boolean waiting = false;

     private UploadCompleteBroadcastReceiver registrationreceiver = null;
     private UploadCompleteBroadcastReceiver loginreceiver = null;

     private Dialog dialog;

     private Context context;

     private volatile boolean authenticated = false;
     private volatile boolean oldauthstatus = false;

     private long uid = 0;

     private Random rand = null;

     private String ruser = "";
     private String rpass = "";

     public AuthenticateDialog(final Context context)
     {
                     this.context = context;
                     rand = new Random();

                     for (int i = 0; i < 16; i++)
                     {
                                     ruser += rand.nextInt(10);
                                     rpass += rand.nextInt(10);
                     }

                     dialog = new Dialog(context, 0)
                     {
                                     @Override
                                     public void
onBackPressed()
                                     {
                                                     super.onBackPressed();
                                                     if (registrationreceiver != null)
                                                     {
                                                                     context.unregisterReceiver(registrationreceiver);
                                                     }
                                                     registrationreceiver = null;
                                                     if (loginreceiver != null)
                                                     {
                                                                     context.unregisterReceiver(loginreceiver);
                                                     }
                                                     loginreceiver = null;
                                                     waiting = false;
                                                     this.cancel();
                                     }

                                     @Override
                                     public void onStop()
                                     {
                                                     super.onStop();
                                                     if (registrationreceiver != null)
                                                     {
                                                                     context.unregisterReceiver(registrationreceiver);
                                                     }
                                                     registrationreceiver = null;
                                                     if (loginreceiver != null)
                                                     {
                                                                     context.unregisterReceiver(loginreceiver);
                                                     }
                                                     loginreceiver = null;
                                                     waiting = false;
                                     }
                     };
                     dialog.setContentView(R.layout.dialog_authenticate);
                     dialog.setTitle(null);

                     inputtxt = new EditText[3];
                     inputtxt[0] = (EditText) dialog.findViewById(R.id.inputusername);
                     inputtxt[1] = (EditText) dialog.findViewById(R.id.inputuserpass);
                     inputtxt[2] = (EditText) dialog.findViewById(R.id.inputcallsign);

                     inputtxt[0].setText(ruser);
                     inputtxt[1].setText(rpass);

                     btnaccount = new Button[2];
                     btnaccount[0] = (Button) dialog.findViewById(R.id.btnlogin);
                     btnaccount[1] = (Button) dialog.findViewById(R.id.btnregister);

                     btnaccount[0].setOnClickListener(new View.OnClickListener()
                     {
                                     // attempt to login...
                                     @SuppressLint("InlinedApi")

                                     @Override
                                     public void onClick(View v)
                                     {
                                                     if (waiting)
                                                     {
                                                                     newtoast("Please wait....attempting to connect");
                                                                     return;
                                                     }
                                                     waiting = true;
                                                     uid = Config.getUniqueID(uid);
                                                     Intent serviceintent = new Intent(context, UploadService.class);
                                                     if (Build.VERSION.SDK_INT >= 12)
                                                     {
                                                                     serviceintent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
                                                     }
                                                     serviceintent.setAction("com.lloydm.geosword.common.UploadService.login");

                                                     serviceintent.putExtra("com.lloydm.geosword.activities.AuthenticateActivity.username", inputtxt[0].getText().toString());
                                                     serviceintent.putExtra("com.lloydm.geosword.activities.AuthenticateActivity.userpass", inputtxt[1].getText().toString());
                                                     serviceintent.putExtra("com.lloydm.geosword.common.UploadService.uniqueid", uid);
                                                     context.startService(serviceintent);
                                     }
                     });
                     btnaccount[1].setOnClickListener(new View.OnClickListener()
                     {
                                     // attempt to register
                                     @SuppressLint("InlinedApi")

                                     @Override
                                     public void onClick(View v)
                                     {
                                                     if (waiting)
                                                     {
                                                                     newtoast("Please wait....attempting to connect");
                                                                     return;
                                                     }
                                                     waiting = true;
                                                     uid = Config.getUniqueID(uid);
                                                     Intent serviceintent = new Intent(context, UploadService.class);
                                                     if (Build.VERSION.SDK_INT >= 12)
                                                     {
                                                                     serviceintent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
                                                     }
                                                     serviceintent.setAction("com.lloydm.geosword.common.UploadService.newuser");

                                                     serviceintent.putExtra("com.lloydm.geosword.activities.AuthenticateActivity.newusername", inputtxt[0].getText().toString());
                                                     serviceintent.putExtra("com.lloydm.geosword.activities.AuthenticateActivity.newuserpass", inputtxt[1].getText().toString());
                                                     serviceintent.putExtra("com.lloydm.geosword.activities.AuthenticateActivity.newscreenname", inputtxt[2].getText().toString());
                                                     serviceintent.putExtra("com.lloydm.geosword.common.UploadService.uniqueid", uid);
                                                     context.startService(serviceintent);
                                     }
                     });
     }

     public boolean isauthenticated()
     {
                     return authenticated;
     }

     public boolean authstatuschanged()
     {
                     if (oldauthstatus != authenticated)
                     {
                                     return true;
                     }
                     return false;
     }

     public void show()
     {
                     setreceiver();
                     oldauthstatus = authenticated;
                     authenticated = false;
                     // fill the username etc with the user's current username....
                     SharedPreferences sp = context.getSharedPreferences("com.lloydm.geosword", Activity.MODE_PRIVATE);
                     final String username = sp.getString("com.lloydm.geosword.username", ruser);
                     final String password = sp.getString("com.lloydm.geosword.userpass", rpass);
                     final String callsign = sp.getString("com.lloydm.geosword.callsign", "");
                     ((Activity) context).runOnUiThread(new Runnable()
                     {
                                     @Override
                                     public void
run()
                                     {
                                                     inputtxt[0].setText(username);
                                                     inputtxt[1].setText(password);
                                                     inputtxt[2].setText(callsign);
                                     }
                     });
                     dialog.show();
     }

     private void newtoast(final String txt)
     {
                     ((Activity) context).runOnUiThread(new Runnable()
                     {

                                     @Override
                                     public void
run()
                                     {
                                                     Toast.makeText(context, txt, Toast.LENGTH_SHORT).show();

                                     }
                     });
     }

     private void setreceiver()
     {
                     if (registrationreceiver == null)
                     {
                                     registrationreceiver = new UploadCompleteBroadcastReceiver()
                                     {
                                                     @Override
                                                     public void onReceive(Context context, Intent intent)
                                                     {

                                                                     long tuid = intent.getLongExtra("com.lloydm.geosword.common.UploadService.uniqueid", -1);
                                                                     if (tuid != uid)
                                                                     {
                                                                                     // ignore this one and try again.....
                                                                                     Log.i(TAG, "uid does not match");
                                                                                     // waiting = false;
                                                                                     // return;
                                                                     }

                                                                     boolean resultcode = intent.getBooleanExtra("com.lloydm.geosword.activities.AuthenticateActivity.resultcode", false);
                                                                     int reason = intent.getIntExtra("com.lloydm.geosword.activities.AuthenticateActivity.reason", -1);

                                                                     if (!resultcode)
                                                                     {
                                                                                     // failed for some reason...
                                                                                     switch (reason)
                                                                                     {

                                                                                     case UploadService.REGISTER_BAD_CREDENTIALS:

                                                                                                     newtoast("Username, Password or Callsign are invalid");
                                                                                                     break;

                                                                                     case UploadService.REGISTER_INVALID_USER:

                                                                                                     newtoast("Username, Password or Callsign are invalid");
                                                                                                     break;

                                                                                     case UploadService.REGISTER_WEB_ERROR:
                                                                                                     newtoast("Network error");
                                                                                                     break;

                                                                                     default:
                                                                                                     newtoast("Unspecified error");
                                                                                                     break;
                                                                                     }
                                                                     }
                                                                     else
                                                                     {
                                                                                     // okay we've registered and have logged in.....
                                                                                     // let the user know and exit the fragment....
                                                                                     newtoast("Registered and Logged in...");
                                                                                     // this could change some things in unexpected ways......be careful ***** (moved from below the dialog.dismiss();)
                                                                                     oldauthstatus = authenticated;
                                                                                     authenticated = true;
                                                                                     try
                                                                                     {
                                                                                                     dialog.dismiss();
                                                                                     }
                                                                                     catch (Exception e)
                                                                                     {
                                                                                                     Log.e(TAG, "Dialog either null or not showing");
                                                                                     }
                                                                     }
                                                                     waiting = false;
                                                     }
                                     };
                                     context.registerReceiver(registrationreceiver, new IntentFilter("com.lloydm.geosword.activities.AuthenticateActivity.newuser"));
                     }
                     if (loginreceiver == null)
                     {
                                     loginreceiver = new UploadCompleteBroadcastReceiver()
                                     {
                                                     @Override
                                                     public void onReceive(Context context, Intent intent)
                                                     {
                                                                     long tuid = intent.getLongExtra("com.lloydm.geosword.common.UploadService.uniqueid", -1);
                                                                     if (tuid != uid)
                                                                     {
                                                                                     // ignore this one and try again.....
                                                                                     Log.i(TAG, "uid does not match");
                                                                                     // waiting = false;
                                                                                     // return;
                                                                     }

                                                                     boolean resultcode = intent.getBooleanExtra("com.lloydm.geosword.activities.AuthenticateActivity.resultcode", false);
                                                                     int reason = intent.getIntExtra("com.lloydm.geosword.activities.AuthenticateActivity.reason", -1);
                                                                     if (!resultcode)
                                                                     {
                                                                                     // failed for some reason...
                                                                                     switch (reason)
                                                                                     {

                                                                                     case UploadService.LOGIN_NOT_FOUND:

                                                                                                     newtoast("Username, Password or Callsign are invalid");
                                                                                                     break;

                                                                                     case UploadService.LOGIN_WEB_ERROR:
                                                                                                     newtoast("Network error");
                                                                                                     break;

                                                                                     default:
                                                                                                     newtoast("Unspecified error");
                                                                                                     break;
                                                                                     }
                                                                     }
                                                                     else
                                                                     {
                                                                                     // okay we've registered and have logged in.....
                                                                                     // let the user know and exit the fragment....
                                                                                     newtoast("Logged in...");
                                                                                     try
                                                                                     {
                                                                                                     dialog.dismiss();
                                                                                     }
                                                                                     catch (Exception e)
                                                                                     {
                                                                                                     Log.e(TAG, "Dialog either null or not showing");
                                                                                     }
                                                                                     oldauthstatus = authenticated;
                                                                                     authenticated = true;
                                                                     }
                                                                     waiting = false;
                                                     }
                                     };
                                     context.registerReceiver(loginreceiver, new IntentFilter("com.lloydm.geosword.activities.AuthenticateActivity.login"));
                     }
     }

}