package com.cpm.lorealbaautomation;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;

import com.google.firebase.messaging.FirebaseMessaging;
import com.cpm.lorealbaautomation.delegates.PrefHelper;

import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.gson.Gson;
import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.constant.AlertandMessages;
import com.cpm.lorealbaautomation.constant.CommonFunctions;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.dailyactivity.NotificationDetailActivity;
import com.cpm.lorealbaautomation.dailyactivity.TabLoginActivity;
import com.cpm.lorealbaautomation.gettersetter.LoginGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.BaListGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.JCPGetterSetter;
import com.cpm.lorealbaautomation.gsonGetterSetter.TableStructure;
import com.cpm.lorealbaautomation.gsonGetterSetter.TableStructureGetterSetter;
import com.cpm.lorealbaautomation.retrofit.DownloadAllDatawithRetro;
import com.cpm.lorealbaautomation.retrofit.PostApi;
import com.cpm.lorealbaautomation.retrofit.UploadDataWithRetrofit;

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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class UserLoginActivity extends AppCompatActivity implements View.OnClickListener {
    String counterId = "", visitdate = "", jsonString = "", result = "", counterName = "", counter_code = "", title = "", body = "", path = "", type;
    SharedPreferences preferences;
    private SharedPreferences.Editor editor = null;
    private Context context;
    LinearLayout lay_ba, lay_ma, lay_tba;
    Button btncontinue;
    String userId;
    Lorealba_Database db;
    int downloadindex = 0;
    ProgressDialog loading = null;
    ArrayList<BaListGetterSetter> bsListData = new ArrayList<>();
    ArrayList<LoginGetterSetter> allLoginListData = new ArrayList<>();
    EditText user_password;
    String TAG = getClass().getSimpleName();
    JSONObject jsonObject = new JSONObject();
    TextView counter_name, versioncode_txt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_user_login);
        getViewId();

        FirebaseMessaging.getInstance().getToken()
                .addOnCompleteListener(task -> {
                    if (!task.isSuccessful()) {
                        Log.w(TAG, "Fetching FCM registration token failed", task.getException());
                        return;
                    }

                    // Get new FCM registration token
                    String token = task.getResult();
                    try {
                        jsonObject.put("CounterId", counterId);
                        jsonObject.put("RegistrationId", token);
                        jsonString = jsonObject.toString();
                        UploadDataWithRetrofit upload = new UploadDataWithRetrofit(context);
                        result = upload.uploadDeviceTokenDetails(jsonString, CommonString.UPLOAD_DEVICE_TOKEN_DETAILS);
                    } catch (JSONException e) {
                        e.fillInStackTrace();
                    }

                    // Log and toast
                    //test(TAG, "Token: " + token);
                });


    }


    @SuppressLint("SetTextI18n")
    void getViewId() {
        context = this;
        db = new Lorealba_Database(context);
        db.open();
        preferences = PrefHelper.getPrefs(context);
        editor = preferences.edit();
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        lay_ba = (LinearLayout) findViewById(R.id.lay_ba);
        lay_ma = (LinearLayout) findViewById(R.id.lay_ma);
        lay_tba = (LinearLayout) findViewById(R.id.lay_tba);
        btncontinue = (Button) findViewById(R.id.btncontinue);

        user_password = (EditText) findViewById(R.id.user_password);
        counter_name = (TextView) findViewById(R.id.counter_name);
        versioncode_txt = (TextView) findViewById(R.id.versioncode_txt);
        setSupportActionBar(toolbar);
        Objects.requireNonNull(getSupportActionBar()).setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle(getString(R.string.user_login));

        counterId = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        counter_code = preferences.getString(CommonString.KEY_COUNTER_CODE, "");
        counterName = preferences.getString(CommonString.KEY_COUNTER_NAME, "");
        visitdate = preferences.getString(CommonString.KEY_DATE, "");
        counter_name.setText("Counter Name : " + counterName + "\n" + "Counter Code : " + counter_code);
        lay_ba.setOnClickListener(this);
        lay_ma.setOnClickListener(this);
        lay_tba.setOnClickListener(this);
        btncontinue.setOnClickListener(this);
        checkAndRequestPermissions();

        bsListData = db.getBAListAllData(visitdate, counterId);
        if (bsListData.size() == 0) {
            UploadDataTask();
        }

        if (getIntent().getExtras() != null) {
            for (String key : getIntent().getExtras().keySet()) {
                if (key.equalsIgnoreCase("title")) {
                    title = getIntent().getExtras().getString(key);
                } else if (key.equalsIgnoreCase("body")) {
                    body = getIntent().getExtras().getString(key);
                } else if (key.equalsIgnoreCase("path")) {
                    path = getIntent().getExtras().getString(key);
                } else if (key.equalsIgnoreCase("type")) {
                    type = getIntent().getExtras().getString(key);
                }
            }

            assert title != null;
            assert body != null;
            if (!title.equalsIgnoreCase("") && !body.equalsIgnoreCase("")) {
                db.open();
                long value = db.insertNotificationData(title, body, path, visitdate, type, counterId);
                if (value > 0) {
                    Toast.makeText(context, "Notification Inserted", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "Notification Not Inserted", Toast.LENGTH_SHORT).show();
                }
            }

            if (!title.equals("")) {
                Intent in = new Intent(this, NotificationDetailActivity.class);
                in.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                in.putExtra("Type", type);
                in.putExtra("Title", title);
                in.putExtra("Body", body);
                in.putExtra("Path", path);
                startActivity(in);
            }
        }
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.lay_ba) {
            db.open();
            if (db.getBAListAllData(visitdate, counterId).size() > 0) {
                editor.putString(CommonString.TAG_FROM, CommonString.TAG_FROM_BA);
                editor.putString(CommonString.TAG_MODE, CommonString.MODE_FROM_BA_LOGIN);
                editor.putString(CommonString.KEY_USER_TYPE, CommonString.TAG_FROM_BA);
                editor.commit();

                Intent balogin = new Intent(context, TabLoginActivity.class);
                balogin.putExtra(CommonString.TAG_FROM, CommonString.TAG_FROM_BA);
                balogin.putExtra(CommonString.TAG_MODE, CommonString.MODE_FROM_BA_LOGIN);
                startActivity(balogin);
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
            } else {
                DownloadData(CommonString.TAG_FROM_BA);
            }

        } else if (v.getId() == R.id.lay_ma) {
            db.open();
            if (db.getBAListAllData(visitdate, counterId).size() > 0) {
                editor.putString(CommonString.TAG_FROM, CommonString.TAG_FROM_ME);
                editor.putString(CommonString.TAG_MODE, CommonString.MODE_FROM_ME_LOGIN);
                editor.putString(CommonString.KEY_USER_TYPE, CommonString.TAG_FROM_ME);
                editor.commit();
                Intent malogin = new Intent(context, TabLoginActivity.class);
                malogin.putExtra(CommonString.TAG_FROM, CommonString.TAG_FROM_ME);
                malogin.putExtra(CommonString.TAG_MODE, CommonString.MODE_FROM_ME_LOGIN);
                startActivity(malogin);
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
            } else {
                DownloadData(CommonString.TAG_FROM_ME);
            }


        } else if (v.getId() == R.id.lay_tba) {
            db.open();
            if (db.getBAListAllData(visitdate, counterId).size() > 0) {
                editor.putString(CommonString.TAG_FROM, CommonString.TAG_FROM_TBA);
                editor.putString(CommonString.TAG_MODE, CommonString.MODE_FROM_TBA_LOGIN);
                editor.putString(CommonString.KEY_USER_TYPE, CommonString.TAG_FROM_TBA);
                editor.commit();

                Intent tbalogin = new Intent(context, TabLoginActivity.class);
                tbalogin.putExtra(CommonString.TAG_FROM, CommonString.TAG_FROM_TBA);
                tbalogin.putExtra(CommonString.TAG_MODE, CommonString.MODE_FROM_TBA_LOGIN);
                startActivity(tbalogin);
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);

            } else {
                DownloadData(CommonString.TAG_FROM_TBA);
            }

        }
    }

    public void UploadDataTask() {
        try {
            ArrayList<String> keysList = new ArrayList<>();
            ArrayList<String> jsonList = new ArrayList<>();
            ArrayList<String> KeyNames = new ArrayList<>();
            keysList.add("Table_Structure");
            keysList.add("BA_List");
            keysList.add("Mapping_JourneyPlan");
            keysList.size();
            for (int i = 0; i < keysList.size(); i++) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("Downloadtype", keysList.get(i));
                jsonObject.put("Username", "");
                jsonObject.put("Param1", counterId);
                jsonObject.put("Param2", "");
                jsonList.add(jsonObject.toString());
                KeyNames.add(keysList.get(i));
            }
            if (jsonList.size() > 0) {
                ProgressDialog pd = new ProgressDialog(context);
                DownloadAllDatawithRetro downloadData = new DownloadAllDatawithRetro(context, db, pd, CommonString.TAG_FROM_CURRENT);
                downloadData.listSize = jsonList.size();
                downloadData.downloadDataUniversalBa(jsonList, KeyNames, downloadindex, CommonString.DOWNLOAD_ALL_SERVICE);
            }

        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }


    @SuppressLint("SetTextI18n")
    @Override
    protected void onResume() {
        super.onResume();
        db.open();
        allLoginListData = db.getlistAllData(visitdate, userId);
        checkAndRequestPermissions();
        try {
            PackageInfo pInfo = context.getPackageManager().getPackageInfo(getPackageName(), 0);
            String version = pInfo.versionName;
            versioncode_txt.setText("Version : " + version);
        } catch (PackageManager.NameNotFoundException e) {
            e.fillInStackTrace();
            versioncode_txt.setText("Version : 0.0");
        }
    }


    private boolean checkAndRequestPermissions() {
        int CAMERA = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
        int ACCESS_NETWORK_STATE = ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_NETWORK_STATE);
        int ACCESS_COARSE_LOCATION = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);
        int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
        int READ_PHONE_STATE = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);
        List<String> listPermissionsNeeded = new ArrayList<>();

        if (CAMERA != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.CAMERA);
        }

        if (ACCESS_NETWORK_STATE != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.ACCESS_NETWORK_STATE);
        }
        if (ACCESS_COARSE_LOCATION != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }
        if (locationPermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }

        if (READ_PHONE_STATE != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.READ_PHONE_STATE);
        }


        if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), CommonString.PERMISSION_ALL);
            return false;
        }

        return true;
    }

    private void showDialogOK(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(this).setMessage(message).setPositiveButton("OK", okListener).setNegativeButton("Cancel", okListener).create().show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String permissions[], @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //test("", "Permission callback called-------");
        switch (requestCode) {
            case CommonString.PERMISSION_ALL: {
                Map<String, Integer> perms = new HashMap<>();
                // Initialize the map with both permissions
                perms.put(Manifest.permission.CAMERA, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.ACCESS_NETWORK_STATE, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.READ_PHONE_STATE, PackageManager.PERMISSION_GRANTED);
                // Fill with actual results from user
                if (grantResults.length > 0) {
                    for (int i = 0; i < permissions.length; i++)
                        perms.put(permissions[i], grantResults[i]);
                    // Check for both permissions
                    boolean allPermissionsGranted =
                            Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.CAMERA)) &&
                                    Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_NETWORK_STATE)) &&
                                    Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_COARSE_LOCATION)) &&
                                    Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.ACCESS_FINE_LOCATION)) &&
                                    Integer.valueOf(PackageManager.PERMISSION_GRANTED).equals(perms.get(Manifest.permission.READ_PHONE_STATE));
                    if (allPermissionsGranted) {

                    }
                } else {
                    //test("", "Some permissions are not granted ask again ");
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) ||
                            ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_NETWORK_STATE) ||
                            ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION) ||
                            ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION) ||
                            ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)) {
                        showDialogOK("Location,File,Call and Camera Services Permission required for this app", (dialog, which) -> {
                            switch (which) {
                                case DialogInterface.BUTTON_POSITIVE:
                                    checkAndRequestPermissions();
                                    break;
                                case DialogInterface.BUTTON_NEGATIVE:
                                    // proceed with logic by disabling the related features or quit the app.
                                    Intent startMain = new Intent(Intent.ACTION_MAIN);
                                    startMain.addCategory(Intent.CATEGORY_HOME);
                                    startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                    startActivity(startMain);
                                    break;
                            }
                        });
                    }
                    //permission is denied (and never ask again is  checked)
                    //shouldShowRequestPermissionRationale will return false
                    else {
                        Toast.makeText(this, "Go to settings and enable permissions", Toast.LENGTH_LONG).show();
                        //                           //proceed with logic by disabling the related features or quit the app.
                    }
                }
            }
        }
    }

    public void DownloadData(String userType) {
        try {
            if (CommonFunctions.checkNetIsAvailable(context)) {
                ArrayList<String> keysList = new ArrayList<>();
                ArrayList<String> jsonList = new ArrayList<>();
                ArrayList<String> KeyNames = new ArrayList<>();
                keysList.add("Table_Structure");
                keysList.add("BA_List");
                keysList.add("Mapping_JourneyPlan");
                keysList.size();
                for (int i = 0; i < keysList.size(); i++) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("Downloadtype", keysList.get(i));
                    jsonObject.put("Username", "");
                    jsonObject.put("Param1", counterId);
                    jsonObject.put("Param2", "");
                    jsonList.add(jsonObject.toString());
                    KeyNames.add(keysList.get(i));
                }

                if (jsonList.size() > 0) {
                    loading = ProgressDialog.show(context, "Downloading", "Please wait...", false, true);
                    downloadBaList(context, jsonList, KeyNames, downloadindex, userType, loading);
                }

            } else {
                AlertandMessages.showToastMsg(context, getString(R.string.nonetwork));
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    public void downloadBaList(final Context context, final ArrayList<String> jsonStringList, final ArrayList<String> KeyNames, int downloadindex, final String userType, final ProgressDialog loading) {
        final String[] data_global = {""};
        String jsonString = "", KeyName = "";
        int jsonIndex = 0;
        if (jsonStringList.size() > 0) {
            OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT,
                    TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
            jsonString = jsonStringList.get(downloadindex);
            KeyName = KeyNames.get(downloadindex);
            jsonIndex = downloadindex;

            RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString);
            Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
            PostApi api = adapter.create(PostApi.class);
            Call<String> call = api.getDownloadAll(jsonData);
            final int[] finalJsonIndex = {jsonIndex};
            final String finalKeyName = KeyName;

            call.enqueue(new Callback<String>() {
                @Override
                public void onResponse(@NonNull Call<String> call, @NonNull Response<String> response) {
                    String responseBody = response.body();
                    String data = null;
                    if (responseBody != null && response.isSuccessful()) {
                        try {
                            data = response.body();
                            if (data.equals("")) {
                                data_global[0] = "";
                            } else {
                                data_global[0] = data;
                                if (finalKeyName.equalsIgnoreCase("Table_Structure")) {
                                    TableStructureGetterSetter tableStructureObj = new Gson().fromJson(data, TableStructureGetterSetter.class);
                                    String isAllTableCreated = createTable(tableStructureObj);

                                    if (isAllTableCreated != CommonString.KEY_SUCCESS) {
                                        loading.dismiss();
                                        if (loading != null && loading.isShowing()) {
                                            loading.dismiss();
                                        }

                                        AlertandMessages.showAlert((Activity) context, isAllTableCreated + " not created", true);
                                    }
                                } else {
                                    switch (finalKeyName) {
                                        case "BA_List":
                                            if (!data.contains("No Data")) {
                                                JCPGetterSetter baListObject = new Gson().fromJson(data, JCPGetterSetter.class);
                                                if (baListObject != null && !db.insertBalistData(baListObject)) {
                                                    AlertandMessages.showToastMsg(context, "Ba List data not saved");
                                                }
                                            } else {
                                                throw new Exception();
                                            }

                                            break;

                                        case "Mapping_JourneyPlan":
                                            if (!data.contains("No Data")) {
                                                JCPGetterSetter jcpObject = new Gson().fromJson(data, JCPGetterSetter.class);
                                                if (jcpObject != null && !db.insertJCPData(jcpObject)) {
                                                    AlertandMessages.showToastMsg(context, "JCP data not saved");
                                                }
                                            }

                                            break;
                                    }
                                }
                            }

                            finalJsonIndex[0]++;
                            if (finalJsonIndex[0] != KeyNames.size()) {
                                downloadBaList(context, jsonStringList, KeyNames, finalJsonIndex[0], userType, loading);
                            } else {
                                loading.dismiss();

                                if (loading != null && loading.isShowing()) {
                                    loading.dismiss();
                                }

                                AlertandMessages.showToastMsg(context, "BA List data downloaded Successfully");

                                if (userType.equalsIgnoreCase(CommonString.TAG_FROM_BA)) {
                                    editor.putString(CommonString.TAG_FROM, CommonString.TAG_FROM_BA);
                                    editor.putString(CommonString.TAG_MODE, CommonString.MODE_FROM_BA_LOGIN);
                                    editor.putString(CommonString.KEY_USER_TYPE, CommonString.TAG_FROM_BA);
                                    editor.commit();

                                    Intent balogin = new Intent(context, TabLoginActivity.class);
                                    balogin.putExtra(CommonString.TAG_FROM, CommonString.TAG_FROM_BA);
                                    balogin.putExtra(CommonString.TAG_MODE, CommonString.MODE_FROM_BA_LOGIN);
                                    startActivity(balogin);
                                    overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                } else if (userType.equalsIgnoreCase(CommonString.TAG_FROM_ME)) {

                                    editor.putString(CommonString.TAG_FROM, CommonString.TAG_FROM_ME);
                                    editor.putString(CommonString.TAG_MODE, CommonString.MODE_FROM_ME_LOGIN);
                                    editor.putString(CommonString.KEY_USER_TYPE, CommonString.TAG_FROM_ME);
                                    editor.commit();

                                    Intent malogin = new Intent(context, TabLoginActivity.class);
                                    malogin.putExtra(CommonString.TAG_FROM, CommonString.TAG_FROM_ME);
                                    malogin.putExtra(CommonString.TAG_MODE, CommonString.MODE_FROM_ME_LOGIN);
                                    startActivity(malogin);
                                    overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                } else if (userType.equalsIgnoreCase(CommonString.TAG_FROM_TBA)) {

                                    editor.putString(CommonString.TAG_FROM, CommonString.TAG_FROM_TBA);
                                    editor.putString(CommonString.TAG_MODE, CommonString.MODE_FROM_TBA_LOGIN);
                                    editor.putString(CommonString.KEY_USER_TYPE, CommonString.TAG_FROM_TBA);
                                    editor.commit();

                                    Intent tbalogin = new Intent(context, TabLoginActivity.class);
                                    tbalogin.putExtra(CommonString.TAG_FROM, CommonString.TAG_FROM_TBA);
                                    tbalogin.putExtra(CommonString.TAG_MODE, CommonString.MODE_FROM_TBA_LOGIN);
                                    startActivity(tbalogin);
                                    overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                }
                            }

                        } catch (Exception e) {
                            e.fillInStackTrace();
                            loading.dismiss();

                            if (loading != null && loading.isShowing()) {
                                loading.dismiss();
                            }

                            AlertandMessages.showToastMsg(context, "Ba List Data Not Found. Please Contact To Supervisor");

                        }
                    } else {
                        loading.dismiss();
                        if (loading != null && loading.isShowing()) {
                            loading.dismiss();
                        }
                        AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_NO_RESPONSE_SERVER);
                    }
                }

                @Override
                public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
                    loading.dismiss();
                    if (loading != null && loading.isShowing()) {
                        loading.dismiss();
                    }

                    AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION);
                }
            });
        }
    }

    String createTable(TableStructureGetterSetter tableGetSet) {
        List<TableStructure> tableList = tableGetSet.getTableStructure();
        for (int i = 0; i < tableList.size(); i++) {
            String table = tableList.get(i).getSqlText();
            if (db.createtable(table) == 0) {
                return table;
            }
        }
        return CommonString.KEY_SUCCESS;
    }
}
