package com.unibuy.smartdevice;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.widget.Toast;

import androidx.activity.OnBackPressedCallback;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;

import com.unibuy.smartdevice.exception.Logs;
import com.unibuy.smartdevice.tools.HandlerMain;
import com.unibuy.smartdevice.tools.Tools;
import com.unibuy.smartdevice.utils.LanguageHelper;

public abstract class AppCompatActivityAbstract extends AppCompatActivity {
    private Context ctx;
    private Logs logs;
    private Tools tools;
    private HandlerMain handlerMain;

    public Context getCtx() {
        return ctx;
    }

    public Logs getLogs() {
        return logs;
    }

    public Tools getTools() {
        return tools;
    }

    public HandlerMain getHandlerMain() {
        return handlerMain;
    }

    protected abstract Context setCtx();
    protected abstract Class<?> setCls();
    protected abstract HandlerMain setHandlerMain();
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 讀取最後設定語言的設定
//        LanguageHelper.applySavedLanguage(this);

        ctx = setCtx();
        this.logs = new Logs(setCls());
        Tools.setWindow(getWindow());
        this.tools = new Tools(getCtx(), logs);
        this.handlerMain = setHandlerMain();
        getTools().hideSystemBars((Activity) getCtx());
        getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                callBackOnBackPressed();
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        Tools.setWindow(getWindow());
        getTools().hideSystemBars((Activity) getCtx());
    }

    public void callBackOnBackPressed() {
        FragmentManager fragmentManager = getSupportFragmentManager();
        int backStackCount = fragmentManager.getBackStackEntryCount();
        if (backStackCount == 0) {
            // 沒有上一頁時，顯示提示訊息
            Toast.makeText(this, "無前一頁", Toast.LENGTH_SHORT).show();
        } else {
            // 有上一頁時，返回上一頁
            finish();
        }
    }

    @Override
    public void onUserInteraction() {
        super.onUserInteraction();
        com.unibuy.smartdevice.MyApp.getInstance().updateLastInteraction();
    }
}
