package com.tofly.latte_core.base;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.Toolbar;

import com.tofly.latte_core.config.Latte;
import com.tofly.latte_core.utils.ActivityUtils;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import butterknife.ButterKnife;
import qiu.niorgai.StatusBarCompat;

//baseActivity
public abstract class BaseActivity<P extends IPresenter> extends RxAppCompatActivity implements BaseView {

    protected P mPresenter;
    private ProgressDialog dialog;
    private Toolbar toolbar;
    protected BaseDelegate.CollapsingToolbarLayoutState state;
    private long lastClickTime = 0;

    @SuppressWarnings("unchecked")
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams. SOFT_INPUT_ADJUST_PAN);
        setContentView();
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//竖屏
        StatusBarCompat.translucentStatusBar(this, true);
        ActivityUtils.getInstance().addActivity(this);
        ButterKnife.bind(this);
        mPresenter = createPresenter();
        if (mPresenter != null) {
            mPresenter.onMvpAttachView(this, savedInstanceState);
        }
        dialog = new ProgressDialog(this);
        dialog.setCancelable(false);
        initView();
        initNet();
    }

    protected void initToolBar(Toolbar toolbar, String title) {
        initToolBar(toolbar);
        setToolBarTitle(title);
    }

    protected void initToolBar(Toolbar toolbar) {
        this.toolbar = toolbar;
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.setDisplayHomeAsUpEnabled(true);
            }
            toolbar.setNavigationOnClickListener(v -> super.onBackPressed());
        }
    }

    protected void setToolBarTitle(String title) {
        getSupportActionBar().setTitle(title);
    }

    public void setDarkStatusBar() {
        Window window = getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
    }

    public void setLightStatusBar() {
        Window window = getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
    }

    public static int getStatusBarHeight(Context context) {
        // 算取状态栏的高
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    public static int getNavigationBarHeight(Context var0) {
        boolean var1 = ViewConfiguration.get(var0).hasPermanentMenuKey();
        int var2;
        return (var2 = var0.getResources().getIdentifier("navigation_bar_height", "dimen", "android")) > 0 && !var1 ? var0.getResources().getDimensionPixelSize(var2) : 0;
    }

    public static int getDialogHeight(Context context) {
        int screenHeight = getScreenHeight(context) - getStatusBarHeight(context) - getNavigationBarHeight(context);
        int dialogHeight = screenHeight;
        return dialogHeight;
    }

    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        Point point = new Point();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            wm.getDefaultDisplay().getRealSize(point);
            return point.y;
        } else {
            DisplayMetrics outMetrics = new DisplayMetrics();
            wm.getDefaultDisplay().getMetrics(outMetrics);
            return outMetrics.heightPixels;
        }
    }

    @Override
    public void onError(String message) {
        if (!TextUtils.isEmpty(message)) {
            Toast toast = Toast.makeText(Latte.getApplicationContext(), message, Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }
    }

    @Override
    public void onEmpty() {

    }

    @Override
    public void showLoading(String msg) {
        if (dialog != null) {
            if (!dialog.isShowing()) {
                dialog.setMessage(msg);
                dialog.show();
            }
        }
    }

    @Override
    public void hideLoading() {
        if (dialog != null) {
            if (dialog.isShowing()) {
                dialog.hide();
            }
        }
    }

    public void setContentView() {
        View view = setLayoutView();
        if (view == null) {
            setContentView(setLayout());
        }else {
            setContentView(view);
        }
    }

    protected abstract P createPresenter();

    public abstract int setLayout();

    public View setLayoutView() {
        return null;
    }

    public abstract void initView();

    public abstract void initNet();

    @Override
    protected void onStart() {
        super.onStart();
        if (mPresenter != null) {
            mPresenter.onMvpStart();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mPresenter != null) {
            mPresenter.onMvpResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mPresenter != null) {
            mPresenter.onMvpPause();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mPresenter != null) {
            mPresenter.onMvpStop();
        }
        if (dialog != null) {
            dialog.dismiss();
        }
    }

    @SuppressWarnings("NullableProblems")
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mPresenter != null) {
            mPresenter.onMvpSaveInstanceState(outState);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityUtils.getInstance().finishActivity(this);
        if (mPresenter != null) {
            mPresenter.onMvpDetachView(false);
            mPresenter.onMvpDestroy();
        }
    }

    public boolean isOverTime() {
        boolean isSuccess = false;
        long currentTime = System.currentTimeMillis();
        long mClickTime = 1000;
        if (currentTime - lastClickTime > mClickTime) {
            lastClickTime = currentTime;
            isSuccess = true;
        }
        return isSuccess;
    }

    public void hideSoftKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null) {
                InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    private static Toast mToast = null;
    public void showToast(String msg) {
        if (mToast == null) {
            mToast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
        } else {
            mToast.setText(msg);
        }
        mToast.show();
    }

    public void showToast(int msg) {
        String text = getResources().getString(msg);
        showToast(text);
    }
}
