package com.cygnusa.hyperm;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.UserResponse;

import java.io.File;
import java.util.Objects;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class SplashScreen extends AppCompatActivity {

    Handler handler = new Handler();
    TransparentProgressDialog progressDialog;
    ApiService restService;
    boolean canGoNotification = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_splash_screen);
        ImageView splashLogo = findViewById(R.id.splashLogo);
        setupWindowAnimations();

        Glide.with(this).load(R.drawable.hyperm_logo).transition(DrawableTransitionOptions.withCrossFade()).into(splashLogo);

        if (getIntent().getExtras() != null) {
            canGoNotification = getIntent().getBooleanExtra("canGoNotification", false);
            if (!canGoNotification) {
                canGoNotification = !getIntent().getExtras().getString("message", "").isEmpty();
            }
        }

        restService = ((MainApplication) getApplication()).getClient();
        GlobalData.openDatabase(SplashScreen.this);

        Cursor cursor = GlobalData.sdb.rawQuery("select * from session", null);
        if (cursor.getCount() == 0) {
            GlobalData.user = null;
            handler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    goLogin();
                }
            }, 5000);
        } else {
            cursor.moveToFirst();
            Gson gson = new Gson();
            GlobalData.user = gson.fromJson(
                    cursor.getString(cursor.getColumnIndex("user")),
                    new TypeToken<UserResponse>() {
                    }.getType());
            try {
                ((MainApplication) getApplication()).addAccessToken(String.format("Bearer %s", GlobalData.user.getAccess_token().trim()));
            } catch (Exception e) {
                e.printStackTrace();
            }
            restService = ((MainApplication) getApplication()).getClient();
            checkToken();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            handler.removeCallbacksAndMessages(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void checkToken() {
        if (new UtilService().isNetworkAvailable(SplashScreen.this)) {
            progressDialog = new TransparentProgressDialog(SplashScreen.this);
            progressDialog.show();

            try {
                restService.getProfile().enqueue(new Callback<UserResponse>() {
                    @Override
                    public void onResponse(Call<UserResponse> call, Response<UserResponse> response) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        if (response.body() != null && response.body().getStatus() == 200) {
                            if (response.body().getData() != null
                                    && response.body().getData().getIs_password_expired().trim().equalsIgnoreCase("1")) {
                                GlobalData.showToast(SplashScreen.this, "Your password is expired, please create new password", Toast.LENGTH_SHORT).show();
                                startActivity(new Intent(getBaseContext(), SetNewPasswordActivity.class));
                                finish();
                            } else {
                                if (GlobalData.user.getData().getIs_profile_updated().equalsIgnoreCase("0")) {
                                    goProfile();
                                } else {
                                    goHome();
                                }
                            }
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                            GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                            goLogin();
                        } else {
                            goLogin();
                        }
                    }

                    @Override
                    public void onFailure(Call<UserResponse> call, Throwable t) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        GlobalData.showToast(getBaseContext(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (Exception e) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
                goLogin();
            }
        } else {
            handler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    if (GlobalData.user == null || GlobalData.user.getData().getIs_profile_updated().equalsIgnoreCase("0")) {

                        goLogin();
                    } else {
                        if (GlobalData.user.getData().getIs_profile_updated().equalsIgnoreCase("0")) {
                            goProfile();
                        } else {
                            goHome();
                        }

                    }
                }
            }, 5000);
        }
    }

    private void setupWindowAnimations() {
        this.overridePendingTransition(R.anim.animation_enter,
                R.anim.animation_leave);
    }

    private void goLogin() {
        getSharedPreferences("FCM_TOKEN", Context.MODE_PRIVATE)
                .edit().putString("FCM_TOKEN_ID", "").apply();
        GlobalData.sdb.delete("session", null, null);
        GlobalData.sdb.delete("topic", null, null);


        if (getPreferences(MODE_PRIVATE).getBoolean("IndroScreen", true)) {
            getPreferences(MODE_PRIVATE).edit().putBoolean("IndroScreen", false).apply();
            startActivity(new Intent(getBaseContext(), IndroScreen.class));
            finish();
        } else {
            startActivity(new Intent(getBaseContext(), LoginActivity.class));
            finish();
        }
    }

    public void deleteLocalFiles() {
        String fileName = Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null)
                + "/" + ".HYPERM/VIDEO";
        File dir = new File(fileName);

        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (String aChildren : children) {
                new File(dir, aChildren).delete();
            }
        }
        File f1 = new File(Objects.requireNonNull(getApplicationContext()).getExternalFilesDir(null) + "/" + ".HYPERM", "PDF");
        if (f1.isDirectory()) {
            String[] children = dir.list();
            for (String aChildren : children) {
                new File(dir, aChildren).delete();
            }
        }
    }

    private void goHome() {
        GlobalData.canLogout = false;
        Intent intent = null;
        if (GlobalData.user.getData().getRole().equalsIgnoreCase("4")
                || GlobalData.user.getData().getRole().equalsIgnoreCase("6")
                || GlobalData.user.getData().getRole().equalsIgnoreCase("7")
                || GlobalData.user.getData().getRole().equalsIgnoreCase("5")
                || GlobalData.user.getData().getRole().equalsIgnoreCase("3")
                || GlobalData.user.getData().getRole().equalsIgnoreCase("14")) {
            intent = new Intent(getBaseContext(),
                    AMHomeActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("canGoNotification", canGoNotification);
            startActivity(intent);
            finish();

        } else if (GlobalData.user.getData().getRole().equalsIgnoreCase("15")) {
            intent = new Intent(getBaseContext(),
                    SEHomeActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("canGoNotification", canGoNotification);
            startActivity(intent);
            finish();
        } else if (GlobalData.user.getData().getRole().equalsIgnoreCase("16")) {
            GlobalData.showToast(getBaseContext(), "You don’t have required permission to log in to the STAR app", Toast.LENGTH_LONG).show();
        } else {
            intent = new Intent(getBaseContext(),
                    HomeActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            intent.putExtra("canGoNotification", canGoNotification);
            startActivity(intent);
            finish();
        }
    }

    private void goProfile() {
        Intent intent = new Intent(getBaseContext(),
                MainProfileActivity.class);
        startActivity(intent);
        finish();
    }
}
