package com.visasoft.eeatex.DB;
import android.content.Context;
import android.os.AsyncTask;
import androidx.room.Room;
import com.visasoft.eeatex.tables.ItemTable;
import java.util.List;
public class DatabaseHelper {
private ASDatabase database;
Context context;
public DatabaseHelper(Context context){
this.context=context;
database= Room.databaseBuilder(context,ASDatabase.class,"APPDB")
.fallbackToDestructiveMigration()
.build();
}
public void insertTask(ItemTable item){
try {
new AsyncInsertItem().execute(item);
}
catch (Exception ex){
ex.printStackTrace();
}
}
private class AsyncInsertItem extends AsyncTask
{
@Override
protected Void doInBackground(ItemTable... itemTables) {
database.asAccess().insertFood(itemTables[0]);
return null;
}
}
public List getAllFood(){
try {
return new AsyncGetFood().execute().get();
}
catch (Exception ex){
return null;
}
}
private class AsyncGetFood extends AsyncTask>
{
@Override
protected List doInBackground(Void... voids) {
return database.asAccess().fetchAllTasks();
}
}
public int getCunt(){
try {
return new AsyncGetCount().execute().get();
}
catch (Exception ex){
return 0;
}
}
private class AsyncGetCount extends AsyncTask
{
@Override
protected Integer doInBackground(Void... voids) {
return database.asAccess().getDataCount();
}
}
public List getPopular(){
try {
return new AsyncGetFood().execute().get();
}
catch (Exception ex){
return null;
}
}
private class AsyncGetPopular extends AsyncTask>
{
@Override
protected List doInBackground(Void... voids) {
return database.asAccess().getPopular();
}
}
}
protected class AsyncGetItem extends AsyncTask {
@Override
protected JsonArray doInBackground(ItemTable... params) {
RestAPI api=new RestAPI();
JsonArray array=null;
try{
JSONStringer userJson = new JSONStringer()
.object()
.key("data")
.object()
.key("last_update").value(params[0].getLast_update())
.key("option").value(8)
.endObject()
.endObject();
String response=api.post("food",userJson);
JsonParser parser=new JsonParser();
array = (JsonArray) parser.parse(response);
}
catch(Exception ex){
System.out.print(ex.toString());
}
return array;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(JsonArray jsonArray) {
try {
DatabaseHelper databaseHelper=new DatabaseHelper(getApplicationContext());
for (int i = 0; i < jsonArray.size(); i++) {
try {
databaseHelper.insertTask(new ItemTable(jsonArray.get(i).getAsJsonObject()));
} catch (Exception e) {
e.printStackTrace();
}
}
editor.putString("last_update",getCurrDateTime());
editor.commit();
}catch (Exception e){
e.printStackTrace();
}
}
}
private String getCurrDateTime(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String currentDateandTime = sdf.format(new Date());
return currentDateandTime;
}
}