package it.integry.integrywmsnative;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.view.LayoutInflater;

import androidx.databinding.DataBindingUtil;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import it.integry.integrywmsnative.core.context.MainContext;
import it.integry.integrywmsnative.core.expansion.BaseActivity;
import it.integry.integrywmsnative.core.expansion.RunnableArgsss;
import it.integry.integrywmsnative.core.settings.SettingsManager;
import it.integry.integrywmsnative.core.utility.PermissionsHelper;
import it.integry.integrywmsnative.core.utility.UtilityContext;
import it.integry.integrywmsnative.databinding.ActivitySplashBinding;
import it.integry.integrywmsnative.gest.login.LoginActivity;
import it.integry.integrywmsnative.gest.main.MainActivity;
import it.integry.integrywmsnative.view.dialogs.base.DialogSimpleMessageView;

public class SplashActivity extends BaseActivity implements MainContext.Listener {


    private ActivitySplashBinding mBinding;

//    private MainContext mainContext = new MainContext(this);

    @Inject
    MainContext mainContext;

    private RunnableArgsss<Integer, String[], List<Integer>> onRequestPermissionResult;

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

        MainApplication.appComponent
                .splashActivityComponent()
                .create()
                .inject(this);

        mainContext.setListener(this);

        mBinding = DataBindingUtil.inflate(LayoutInflater.from(this), R.layout.activity_splash, null, false);
        setContentView(mBinding.getRoot());

        UtilityContext.initMainActivity(this);


        initAppVersion();
        initPermissions(this::init);
    }

    private void initAppVersion() {
        try {
            PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
            String version = pInfo.versionName;

            String debugText = "";

            if (BuildConfig.DEBUG) debugText += "\n[DEBUG VERSION]";

            mBinding.appVersionTextview.setText("v" + version + debugText);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    private void initPermissions(Runnable onComplete) {
        PermissionsHelper.askPermissions(this, onComplete, permanentlyDenied -> {
            if (permanentlyDenied) {
                onError(new SpannableString(getText(R.string.permissions_permanently_denied)));

            } else {
                initPermissions(onComplete);
            }
        });
    }

    private void init() {
        if (!SettingsManager.i().isUserLoggedIn()) {
            startLoginActivity();
        } else {
            mainContext.init();
        }
    }

    @Override
    public void onDBDataLoading(String item) {
        mBinding.loadingInfoTextview.setText("Caricamento " + item);
    }

    @Override
    public void onMenuLoading() {
        mBinding.loadingInfoTextview.setText("Caricamento menù");
    }

    @Override
    public void onContextInitialized() {
        startMainActivity();
    }


    public void setOnRequestPermissionsResult(RunnableArgsss<Integer, String[], List<Integer>> onRequestPermissionResult) {
        this.onRequestPermissionResult = onRequestPermissionResult;
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (this.onRequestPermissionResult != null) {
            List<Integer> grantResultsList = new ArrayList<>();
            for (int i = 0; i < grantResults.length; i++) {
                grantResultsList.add(grantResults[i]);
            }

            this.onRequestPermissionResult.run(requestCode, permissions, grantResultsList);
        }
    }


    private void startLoginActivity() {
        this.finish();
        Intent myIntent = new Intent(this, LoginActivity.class);
        startActivity(myIntent);
    }

    private void startMainActivity() {
        this.finish();
        Intent myIntent = new Intent(this, MainActivity.class);
        startActivity(myIntent);
    }


    @Override
    public void onError(Spanned message) {

        DialogSimpleMessageView.makeErrorDialog(
                message, null, this::finish, R.string.logout, () -> {
                    this.mainContext.logout(MainApplication::exit);
                })
                .show(this.getSupportFragmentManager(), "tag");
    }
}
