package eu.obsys.staffkeeper.ui.worklogin;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.TagLostException;
import android.nfc.tech.Ndef;
import android.nfc.tech.NfcF;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;

import eu.obsys.staffkeeper.FirstPageActivity;
import eu.obsys.staffkeeper.R;
import eu.obsys.staffkeeper.data.JsonObjectAsyncResponse;
import eu.obsys.staffkeeper.data.Repository;
import eu.obsys.staffkeeper.model.GpsLocation;
import eu.obsys.staffkeeper.util.GlobalFunction;

public class WorkLogInActivity extends AppCompatActivity implements NfcAdapter.ReaderCallback {

    private SharedPreferences sharedPreferences;
    private Context context;
    private Button logInToWorkCard,logOutToWorkCard, backToMenu, loginButton;
    private ImageView thumbnail;
    private String bitmapString;
    private TextView nfcContent,txtType;
    private int employeeId = 0;
    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 1888;
    private Drawable sampleImage;

    //NFC
    public static final String MIME_TEXT_PLAIN = "text/plain";
    public static final String TAG = "NfcDemo";
    private Tag detectedTag;
    private NfcAdapter mNfcAdapter;
    PendingIntent pendingIntent;
    IntentFilter[] readTagFilters;

    private String baseUrl;
    private static final String GLOBAL_DATA     = "globalShared";
    String[] perms = {"android.permission.NFC"};

    int permsRequestCode = 200;

    IntentFilter[] intentFiltersArray;

    String[][] techListsArray;
    IntentFilter ndef = new IntentFilter();

    int loginStatus = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_work_log_in);
        requestPermissions(perms, permsRequestCode);
        pendingIntent = PendingIntent.getActivity(
                this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP),
                PendingIntent.FLAG_MUTABLE);
        initVariable();
        initNFC();
        initListener();
    }

    public void initVariable() {
        context                 = getApplicationContext();
        sharedPreferences       = context.getSharedPreferences("placeObject", Context.MODE_PRIVATE);
        baseUrl                 = sharedPreferences.getString("baseUrl", "https://mng.ob-sys.eu/");

        logInToWorkCard         = findViewById(R.id.loginToWorkCard);
        logOutToWorkCard        = findViewById(R.id.logoutFromWorkCard);
        loginButton             = findViewById(R.id.loginButton);
        backToMenu              = findViewById(R.id.bacToMenuButton);
        thumbnail               = findViewById(R.id.PhotoThumbnail);
        nfcContent              = findViewById(R.id.nfcContent);
        nfcContent              = findViewById(R.id.nfcContent);
        nfcContent              = findViewById(R.id.nfcContent);


        sampleImage             = thumbnail.getDrawable();

        PackageManager packageManager = context.getPackageManager();
        if(packageManager.hasSystemFeature(PackageManager.FEATURE_CAMERA_FRONT) == false){
            Toast.makeText(context, "This device does not have a camera.", Toast.LENGTH_LONG)
                    .show();
            return;
        }
    }

    public void takePictureAndStoreEmployeeId(int employeeIdLocal) {
        mNfcAdapter.disableReaderMode(this);
        JSONObject jsonResponse = new Repository().getUserByNFC(baseUrl, employeeIdLocal, WorkLogInActivity.this, new JsonObjectAsyncResponse() {
            @Override
            public void processFinished(JSONObject jsonObject) {
                try {
                    if(jsonObject.getInt("success") == 1) {
                        employeeId = employeeIdLocal;
                        loginStatus = jsonObject.getInt("loginStatus");
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        intent.putExtra("android.intent.extras.CAMERA_FACING", 1);
                        intent.putExtra("android.intent.extra.USE_FRONT_CAMERA", true);

                        startActivityForResult(intent,
                                CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }


    public void initListener() {

        backToMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(WorkLogInActivity.this, FirstPageActivity.class);
                startActivity(intent);
                finish();
            }
        });


        logInToWorkCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logInToWorkCard.setVisibility(View.INVISIBLE);
                Context context = getApplicationContext();
                final int duration                    = Toast.LENGTH_LONG;
//                GpsLocation gpsLocation     = GlobalFunction.getLocation(context);
                new Repository().setLoginStatus(
                        baseUrl,
                        employeeId,
                        1,
                        sharedPreferences.getInt("placeId", 0),
                        bitmapString,
                        WorkLogInActivity.this,
                        new JsonObjectAsyncResponse() {
                            @Override
                            public void processFinished(JSONObject _jsonObject) {
                                try {
                                    if(_jsonObject.getInt("success") == 1) {
                                        logInToWorkCard.setVisibility(View.VISIBLE);
                                        resetPage();
                                    } else {
                                        logInToWorkCard.setVisibility(View.VISIBLE);
                                        String text                   = context.getResources().getString(R.string.faultAction) + " Listener";
                                        Toast toast                   = Toast.makeText(context, text, duration);
                                        toast.show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                );
            }
        });

        logOutToWorkCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                logOutToWorkCard.setVisibility(View.INVISIBLE);
                Context context             = getApplicationContext();
                final int duration          = Toast.LENGTH_SHORT;
                //GpsLocation gpsLocation     = GlobalFunction.getLocation(context);
                new Repository().setLoginStatus(
                        baseUrl,
                        employeeId,
                        0,
                        sharedPreferences.getInt("placeId", 0),
                        bitmapString,
                        WorkLogInActivity.this,
                        new JsonObjectAsyncResponse() {
                            @Override
                            public void processFinished(JSONObject _jsonObject) {
                                try {
                                    if(_jsonObject.getInt("success") == 1) {
                                        logOutToWorkCard.setVisibility(View.VISIBLE);
                                        resetPage();
                                    } else {
                                        logOutToWorkCard.setVisibility(View.VISIBLE);
                                        String text                   = context.getResources().getString(R.string.faultAction) + " Listener";
                                        Toast toast                   = Toast.makeText(context, text, duration);
                                        toast.show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                );
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
            if (resultCode == Activity.RESULT_OK) {

                Bitmap bmp = (Bitmap) data.getExtras().get("data");
                ByteArrayOutputStream stream = new ByteArrayOutputStream();

                bmp.compress(Bitmap.CompressFormat.PNG, 30, stream);
                byte[] byteArray = stream.toByteArray();

                // convert byte array to Bitmap
                bitmapString = Base64.encodeToString(byteArray, Base64.DEFAULT);
                Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0,
                        byteArray.length);
                if(loginStatus == 1) {
                    logInToWorkCard.setVisibility(View.INVISIBLE);
                    logOutToWorkCard.setVisibility(View.VISIBLE);
                } else {
                    logInToWorkCard.setVisibility(View.VISIBLE);
                    logOutToWorkCard.setVisibility(View.INVISIBLE);
                }
//                loginButton.setVisibility(View.INVISIBLE);
                thumbnail.setImageBitmap(bitmap);
            }
        }
    }

    public void resetPage() {
        thumbnail.setImageDrawable(sampleImage);
        logInToWorkCard.setVisibility(View.INVISIBLE);
        logOutToWorkCard.setVisibility(View.INVISIBLE);
    }

    public void initNFC() {
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        try {
            ndef.addDataType("*/*");    /* Handles all MIME based dispatches.
                                       You should specify only the ones that you need. */
        }
        catch (IntentFilter.MalformedMimeTypeException e) {
            throw new RuntimeException("fail", e);
        }
        intentFiltersArray = new IntentFilter[] {ndef, };
        techListsArray = new String[][] { new String[] { NfcF.class.getName() } };

        try {
            if (!mNfcAdapter.isEnabled()) {
                txtType.setText("NFC is disabled.");
            } else {
                //txtType.setText("érkngorbgobrogb");
            }

        } catch (NullPointerException e) {
            Toast.makeText(this, "This device doesn't support NFC.", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        /**
         * It's important, that the activity is in the foreground (resumed). Otherwise
         * an IllegalStateException is thrown.
         */
        if(mNfcAdapter!= null) {

            //mNfcAdapter.enableForegroundDispatch(this, pendingIntent, intentFiltersArray, techListsArray);
            Bundle options = new Bundle();
            // Work around for some broken Nfc firmware implementations that poll the card too fast
            options.putInt(NfcAdapter.EXTRA_READER_PRESENCE_CHECK_DELAY, 250);

            // Enable ReaderMode for all types of card and disable platform sounds
            mNfcAdapter.enableReaderMode(this,
                    this,
                    NfcAdapter.FLAG_READER_NFC_A |
                            NfcAdapter.FLAG_READER_NFC_B |
                            NfcAdapter.FLAG_READER_NFC_F |
                            NfcAdapter.FLAG_READER_NFC_V |
                            NfcAdapter.FLAG_READER_NFC_BARCODE |
                            NfcAdapter.FLAG_READER_NO_PLATFORM_SOUNDS,
                    options);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        /**
         * Call this before onPause, otherwise an IllegalArgumentException is thrown as well.
         */
        if(mNfcAdapter!= null)
            mNfcAdapter.disableReaderMode(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    }

    @Override
    public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(permsRequestCode, permissions, grantResults);

        switch (permsRequestCode) {

            case 200:

                boolean nfcAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;

                break;

        }

    }

    public void onTagDiscovered(Tag tag) {

        // Read and or write to Tag here to the appropriate Tag Technology type class
        // in this example the card should be an Ndef Technology Type
        Ndef mNdef = Ndef.get(tag);

        // Check that it is an Ndef capable card
        if (mNdef != null) {

            // If we want to read
            // As we did not turn on the NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK
            // We can get the cached Ndef message the system read for us.

            NdefMessage mNdefMessage = mNdef.getCachedNdefMessage();
            String anyad = "";
            NdefRecord[] records = mNdefMessage.getRecords();
            for (NdefRecord ndefRecord : records) {
                //if (ndefRecord.getTnf() == NdefRecord.TNF_WELL_KNOWN && Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
                byte[] payload = ndefRecord.getPayload();

                // Get the Text Encoding
                String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16";

                // Get the Language Code
                int languageCodeLength = payload[0] & 0063;

                // String languageCode = new String(payload, 1, languageCodeLength, "US-ASCII");
                // e.g. "en"

                // Get the Text
                try {
                    anyad = new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                // }
            }
            // Or if we want to write a Ndef message

            // Create a Ndef Record
            //NdefRecord mRecord = NdefRecord.createTextRecord("en", "2");

            // Add to a NdefMessage
//            NdefMessage mMsg = new NdefMessage(mRecord);
//
            // Catch errors
            try {
                mNdef.connect();
//                mNdef.writeNdefMessage(mMsg);
                    takePictureAndStoreEmployeeId(Integer.parseInt(anyad));
                    Toast toast = new Toast(getApplicationContext());
                    toast.makeText(getApplicationContext(),"Read NFC Success", Toast.LENGTH_SHORT).show();

                // Make a Sound
                try {
                    Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                    Ringtone r = RingtoneManager.getRingtone(getApplicationContext(),
                            notification);
                    r.play();
                } catch (Exception e) {
                    // Some error playing sound
                }

            //} catch (FormatException e) {
                // if the NDEF Message to write is malformed
            } catch (TagLostException e) {
                // Tag went out of range before operations were complete
            } catch (IOException e) {
                // if there is an I/O failure, or the operation is cancelled
            } finally {
                // Be nice and try and close the tag to
                // Disable I/O operations to the tag from this TagTechnology object, and release resources.
                try {
                    mNdef.close();
                } catch (IOException e) {
                    // if there is an I/O failure, or the operation is cancelled
                }
            }

        }

    }
} 
by

Java online compiler

Write, Run & Share Java code online using OneCompiler's Java online compiler for free. It's one of the robust, feature-rich online compilers for Java language, running the Java LTS version 17. Getting started with the OneCompiler's Java editor is easy and fast. The editor shows sample boilerplate code when you choose language as Java and start coding.

Taking inputs (stdin)

OneCompiler's Java online editor supports stdin and users can give inputs to the programs using the STDIN textbox under the I/O tab. Using Scanner class in Java program, you can read the inputs. Following is a sample program that shows reading STDIN ( A string in this case ).

import java.util.Scanner;
class Input {
    public static void main(String[] args) {
    	Scanner input = new Scanner(System.in);
    	System.out.println("Enter your name: ");
    	String inp = input.next();
    	System.out.println("Hello, " + inp);
    }
}

Adding dependencies

OneCompiler supports Gradle for dependency management. Users can add dependencies in the build.gradle file and use them in their programs. When you add the dependencies for the first time, the first run might be a little slow as we download the dependencies, but the subsequent runs will be faster. Following sample Gradle configuration shows how to add dependencies

apply plugin:'application'
mainClassName = 'HelloWorld'

run { standardInput = System.in }
sourceSets { main { java { srcDir './' } } }

repositories {
    jcenter()
}

dependencies {
    // add dependencies here as below
    implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'
}

About Java

Java is a very popular general-purpose programming language, it is class-based and object-oriented. Java was developed by James Gosling at Sun Microsystems ( later acquired by Oracle) the initial release of Java was in 1995. Java 17 is the latest long-term supported version (LTS). As of today, Java is the world's number one server programming language with a 12 million developer community, 5 million students studying worldwide and it's #1 choice for the cloud development.

Syntax help

Variables

short x = 999; 			// -32768 to 32767
int   x = 99999; 		// -2147483648 to 2147483647
long  x = 99999999999L; // -9223372036854775808 to 9223372036854775807

float x = 1.2;
double x = 99.99d;

byte x = 99; // -128 to 127
char x = 'A';
boolean x = true;

Loops

1. If Else:

When ever you want to perform a set of operations based on a condition If-Else is used.

if(conditional-expression) {
  // code
} else {
  // code
}

Example:

int i = 10;
if(i % 2 == 0) {
  System.out.println("i is even number");
} else {
  System.out.println("i is odd number");
}

2. Switch:

Switch is an alternative to If-Else-If ladder and to select one among many blocks of code.

switch(<conditional-expression>) {    
case value1:    
 // code    
 break;  // optional  
case value2:    
 // code    
 break;  // optional  
...    
    
default:     
 //code to be executed when all the above cases are not matched;    
} 

3. For:

For loop is used to iterate a set of statements based on a condition. Usually for loop is preferred when number of iterations is known in advance.

for(Initialization; Condition; Increment/decrement){  
    //code  
} 

4. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while(<condition>){  
 // code 
}  

5. Do-While:

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {
  // code 
} while (<condition>); 

Classes and Objects

Class is the blueprint of an object, which is also referred as user-defined data type with variables and functions. Object is a basic unit in OOP, and is an instance of the class.

How to create a Class:

class keyword is required to create a class.

Example:

class Mobile {
    public:    // access specifier which specifies that accessibility of class members 
    string name; // string variable (attribute)
    int price; // int variable (attribute)
};

How to create a Object:

Mobile m1 = new Mobile();

How to define methods in a class:

public class Greeting {
    static void hello() {
        System.out.println("Hello.. Happy learning!");
    }

    public static void main(String[] args) {
        hello();
    }
}

Collections

Collection is a group of objects which can be represented as a single unit. Collections are introduced to bring a unified common interface to all the objects.

Collection Framework was introduced since JDK 1.2 which is used to represent and manage Collections and it contains:

  1. Interfaces
  2. Classes
  3. Algorithms

This framework also defines map interfaces and several classes in addition to Collections.

Advantages:

  • High performance
  • Reduces developer's effort
  • Unified architecture which has common methods for all objects.
CollectionDescription
SetSet is a collection of elements which can not contain duplicate values. Set is implemented in HashSets, LinkedHashSets, TreeSet etc
ListList is a ordered collection of elements which can have duplicates. Lists are classified into ArrayList, LinkedList, Vectors
QueueFIFO approach, while instantiating Queue interface you can either choose LinkedList or PriorityQueue.
DequeDeque(Double Ended Queue) is used to add or remove elements from both the ends of the Queue(both head and tail)
MapMap contains key-values pairs which don't have any duplicates. Map is implemented in HashMap, TreeMap etc.