MainActivite.java 17.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450
package com.example.app_10p5;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.ColorDrawable;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.Snackbar;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;;
import android.widget.Toast;

import org.json.JSONObject;

import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;


/**
 * Created by Jean-loup Beaussart on 24/04/2016.
 */
public class MainActivite extends Activity implements ASyncResponse, main_tab_frag.OnFragmentInteractionListener {

    public static final int STATE_RIEN = 0;
    public static final int STATE_COMMANDE = 3;
    public static final int STATE_VIDANGE = 4;
    public static final int STATE_RECHARGEMENT = 2;
    public static final int STATE_CREATION_COMPTE = 1;
    public static final int STATE_CONNEXION = 5;

    public static final long EXPIRATION = 1000*60*10;

    private int mState;
    private String mToken;
    private int mDroit;
    private long mTimeToken;
    private String mUser;

    private NfcAdapter mNfcAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);
        PreferenceManager.setDefaultValues(this, R.xml.preferences, false);

        setTitle(getResources().getString(R.string.app_name));

        mState = STATE_RIEN;
        mTimeToken = -1;
        mToken = "";

        getActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.colorPrimary)));
        mNfcAdapter = NfcAdapter.getDefaultAdapter(getApplicationContext());

        if(savedInstanceState == null){
            FragmentManager fragmentManager = getFragmentManager();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            ConnectionFragment fragment = new ConnectionFragment();
            fragmentTransaction.add(R.id.fragment_container, fragment);
            fragmentTransaction.commit();
        }
        else{
            mTimeToken = savedInstanceState.getLong("timeToken");
            mToken = savedInstanceState.getString("token");
            mState = savedInstanceState.getInt("state");
            mUser = savedInstanceState.getString("user");
            mDroit = savedInstanceState.getInt("droit");
        }
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
       if(item.getItemId() == R.id.action_settings){
           getFragmentManager().beginTransaction().replace(R.id.fragment_container, new SettingsFragment()).addToBackStack("settings").commit();
       }
        else if(item.getItemId() == R.id.action_disconnect){
           disconnect();
       }

       return super.onOptionsItemSelected(item);
    }

    @Override
    public void onFragmentInteraction(String s){

    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState){
        savedInstanceState.putString("token", mToken);
        savedInstanceState.putInt("state", mState);
        savedInstanceState.putString("user", mUser);
        savedInstanceState.putInt("droit", mDroit);
        savedInstanceState.putLong("timeToken", mTimeToken);

        super.onSaveInstanceState(savedInstanceState);
    }

    @Override
    public void onPause() {
        stopForegroundDispatch(this, mNfcAdapter);
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        setupForegroundDispatch(this, mNfcAdapter);
    }

    public static void setupForegroundDispatch(final Activity activity, NfcAdapter adapter){
        if(adapter != null){
            final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass());
            intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            final PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0, intent, 0);
            adapter.enableForegroundDispatch(activity, pendingIntent, null, null);
        }
        else{
            Toast.makeText(activity, "Impossible d'initialiser le NFC", Toast.LENGTH_SHORT).show();
        }
    }

    public static void stopForegroundDispatch(final Activity activity, NfcAdapter adapter) {
        if(adapter != null){
            adapter.disableForegroundDispatch(activity);
        }
        else{
            Toast.makeText(activity, "Impossible d'initialiser le NFC", Toast.LENGTH_SHORT).show();
        }
    }

    public void valideCreationCompte(View v){
        if((TextUtils.getTrimmedLength(mToken) == 30) && ((System.currentTimeMillis() - mTimeToken) < EXPIRATION)) {
            EditText champMontant = (EditText) findViewById(R.id.creation_montant);
            float montant = 0.0f;

            if(!TextUtils.isEmpty(champMontant.getText().toString())){
                try{
                    montant = Float.parseFloat(champMontant.getText().toString());
                }
                catch (Throwable t){
                    Toast.makeText(this, "Remplir le champ montant avec un nombre: " + t.toString(), Toast.LENGTH_LONG).show();
                }

                if(mDroit >= 1){
                    if((montant > 0.0f) && (montant < 200.0f)){
                        mState = STATE_CREATION_COMPTE;
                        champMontant.setText(null);

                        Bundle b = new Bundle();
                        b.putString("token", mToken);
                        b.putInt("state", mState);
                        b.putFloat("montant", montant);


                        NFCFragment nfc = new NFCFragment();
                        nfc.setArguments(b);

                        getFragmentManager().beginTransaction().replace(R.id.fragment_container, nfc).addToBackStack(null).commit();
                    }
                    else{
                        Toast.makeText(this, "Valeur incorrecte.", Toast.LENGTH_LONG).show();
                    }
                }
                else{
                    Toast.makeText(this, "Droit insuffisant.", Toast.LENGTH_LONG).show();
                }
            }
            else{
                champMontant.setError("Montant requis.");
            }
        }
        else{
            disconnect();
        }
    }

    public void valideCommande(View v)
    {
        if((TextUtils.getTrimmedLength(mToken) == 30) && ((System.currentTimeMillis() - mTimeToken) < EXPIRATION)) {
            if(mDroit >= 1){
                mState = STATE_COMMANDE;
                Bundle b = new Bundle();
                b.putString("token", mToken);
                b.putInt("state", mState);

                NFCFragment nfc = new NFCFragment();

                switch (v.getId()){
                    case R.id.commande_validation:
                        EditText champMontant = (EditText) findViewById(R.id.commande_prix);
                        float montant = 0.0f;

                        try{
                            montant = Float.parseFloat(champMontant.getText().toString().replace(",", "."));
                        }
                        catch (Throwable t)
                        {
                            Toast.makeText(this, "Remplir le prix avec un nombre: " + t.toString(), Toast.LENGTH_SHORT).show();
                        }
                        if ((montant > 0.0f) && (montant < 200.0f)) {
                            champMontant.setText(null);
                            b.putFloat("montant", montant);
                            b.putInt("quantite", 0);
                        }
                        else{
                            Toast.makeText(this, "Valeur incorrecte.", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case R.id.button1:
                        b.putInt("quantite", 1);
                        break;
                    case R.id.button2:
                        b.putInt("quantite", 2);
                        break;
                    case R.id.button3:
                        b.putInt("quantite", 3);
                        break;
                    case R.id.button4:
                        b.putInt("quantite", 4);
                        break;
                    case R.id.button5:
                        b.putInt("quantite", 5);
                        break;
                    case R.id.button6:
                        b.putInt("quantite", 6);
                        break;
                }

                nfc.setArguments(b);
                getFragmentManager().beginTransaction().replace(R.id.fragment_container, nfc).addToBackStack(null).commit();
            }
            else{
                Toast.makeText(this, "Droit insuffisant.", Toast.LENGTH_SHORT).show();
            }
        }
        else{
            disconnect();
        }
    }

    public void valideRechargement(View v)
    {
        if((TextUtils.getTrimmedLength(mToken) == 30) && ((System.currentTimeMillis() - mTimeToken) < EXPIRATION)) {
            EditText champMontant = (EditText) findViewById(R.id.rechargement_champ_montant);
            float montant = 0.0f;

            if(!TextUtils.isEmpty(champMontant.getText().toString())){
                try{
                    montant = Float.parseFloat(champMontant.getText().toString());
                }
                catch (Throwable t){
                    Toast.makeText(this, "Remplir le champ montant avec un nombre: " + t.toString(), Toast.LENGTH_LONG).show();
                }

                if(mDroit >= 2){
                    if((montant > 0.0f) && (montant < 200.0f)){
                        mState = STATE_RECHARGEMENT;
                        champMontant.setText(null);

                        Bundle b = new Bundle();
                        b.putString("token", mToken);
                        b.putInt("state", mState);
                        b.putFloat("montant", montant);

                        NFCFragment nfc = new NFCFragment();
                        nfc.setArguments(b);

                        getFragmentManager().beginTransaction().replace(R.id.fragment_container, nfc).addToBackStack(null).commit();
                    }
                    else{
                        Toast.makeText(this, "Valeur incorrecte.", Toast.LENGTH_LONG).show();
                    }
                }
                else{
                    Toast.makeText(this, "Droit insuffisant.", Toast.LENGTH_LONG).show();
                }
            }
            else{
                champMontant.setError("Montant requis.");
            }
        }
        else{
            disconnect();
        }
    }

    public void valideConnection(View v)
    {
        EditText viewUser = (EditText) findViewById(R.id.connection_username);
        EditText viewPsw = (EditText) findViewById(R.id.connection_password);

        String user = viewUser.getText().toString();
        String password = viewPsw.getText().toString();

        if (!TextUtils.isEmpty(user)) {
            if(!TextUtils.isEmpty(password)){
                mState = STATE_CONNEXION;

                viewUser.setText(null);
                viewPsw.setText(null);

                try{
                    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                    URL url = new URL(settings.getString("server_address", null) + "api/utilisateur/connexion");
                    HashMap<String, String> param = new HashMap<String, String>();
                    param.put("login", URLEncoder.encode(user, "UTF-8"));
                    param.put("mdp", URLEncoder.encode(password, "UTF-8"));
                    NetworkThread nt = new NetworkThread(url, param);
                    nt.delegate = this;
                    nt.execute();
                }
                catch (Throwable t) {
                    Toast.makeText(this, "Erreur: " + t.toString(), Toast.LENGTH_LONG).show();
                    System.out.println("Exception: " + t.toString());
                }
            }
            else {
                viewPsw.setError("Mot de passe requis.");
            }
        }
        else{
            viewUser.setError("Utilisateur requis.");
        }
    }

    public void valideVidange(View v){
        if((TextUtils.getTrimmedLength(mToken) == 30) && ((System.currentTimeMillis() - mTimeToken) < EXPIRATION)) {

            if((mDroit >= 2)){
                mState = STATE_VIDANGE;
                Bundle b = new Bundle();
                b.putString("token", mToken);
                b.putInt("state", mState);

                NFCFragment nfc = new NFCFragment();
                nfc.setArguments(b);

                getFragmentManager().beginTransaction().replace(R.id.fragment_container, nfc).addToBackStack(null).commit();
            }
            else{
                Toast.makeText(this, "Droit insuffisant.", Toast.LENGTH_LONG).show();
            }
        }
        else{
            disconnect();
        }
    }

    @Override
    protected void onNewIntent(Intent intent){
        super.onNewIntent(intent);
        Fragment frag = getFragmentManager().findFragmentById(R.id.fragment_container);

        if(mState != STATE_RIEN && frag instanceof NFCFragment){
            NFCFragment nfc = (NFCFragment) frag;
            nfc.handleIntent(intent);
        }
    }

    /* Retour du network thread */
    @Override
    public void processFinish(JSONObject output) {

        if(output.length() != 0){
            try{
                if(output.get("status").toString().equals("ok")){
                    switch (mState){
                        case STATE_COMMANDE:
                            Snackbar.make(findViewById(R.id.coordinator), "Client débité de " + output.get("montant") + "€. " + output.get("soldeAncien") + "€ → " + output.getString("soldeNouveau") + "€", Snackbar.LENGTH_INDEFINITE).show();
                            break;
                        case STATE_CONNEXION:
                            mToken = output.get("jeton").toString();
                            mTimeToken = System.currentTimeMillis();
                            mDroit = output.getInt("droit");
                            mUser = output.get("login").toString();
                            Snackbar.make(findViewById(R.id.coordinator), "Bonjour " + mUser + " vous êtes connecté pour " + EXPIRATION / (1000 * 60) + " minutes.", Snackbar.LENGTH_SHORT).show();
                            getFragmentManager().beginTransaction().replace(R.id.fragment_container, new main_tab_frag()).commit();
                            break;
                        case STATE_CREATION_COMPTE:
                            Snackbar.make(findViewById(R.id.coordinator), "Client créé avec un solde de " + output.get("soldeNouveau") + "€", Snackbar.LENGTH_INDEFINITE).show();
                            break;
                        case STATE_RECHARGEMENT:
                            Snackbar.make(findViewById(R.id.coordinator), "Client rechargé: " + output.get("soldeAncien") + "€ →" + output.get("soldeNouveau") + "€", Snackbar.LENGTH_INDEFINITE).show();
                            break;
                        case STATE_VIDANGE:
                            Snackbar.make(findViewById(R.id.coordinator), "Client vidé: " + output.get("soldeAncien") + "€ → 0€", Snackbar.LENGTH_INDEFINITE).show();
                            break;
                        case STATE_RIEN:
                        default:
                            Toast.makeText(this, "WTF, le cancer est dans l'application!!", Toast.LENGTH_LONG).show();
                            break;
                    }
                }
                else{
                    Toast.makeText(this, "Erreur: " + output.get("status"), Toast.LENGTH_LONG).show();
                }
            }
            catch(Throwable t){
                Toast.makeText(this, "WTF, le cancer est dans l'application!!" + t.toString(), Toast.LENGTH_LONG).show();
            }
        }
        else{
            Toast.makeText(this, "Impossible de se connecter au serveur", Toast.LENGTH_LONG).show();
        }

        mState = STATE_RIEN;
        getFragmentManager().popBackStack();
    }

    public String getToken(){
        return mToken;
    }

    public long getTimeToken(){
        return mTimeToken;
    }

    public void disconnect(){
        mToken = "";
        mDroit = 0;
        mUser = null;
        mTimeToken = -1;
        mState = STATE_RIEN;

        Snackbar.make(findViewById(R.id.coordinator), "Veuillez vous reconnecter", Snackbar.LENGTH_SHORT).show();
        getFragmentManager().beginTransaction().replace(R.id.fragment_container, new ConnectionFragment()).commit();
    }
}