package com.secspace.lib.common.base;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.alibaba.android.arouter.launcher.ARouter;
import com.secspace.lib.common.R;
import com.secspace.lib.common.R2;
import com.secspace.lib.common.utils.ActivityHelper;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;
import pub.devrel.easypermissions.PermissionRequest;

import static android.os.Build.VERSION_CODES.M;


/**
 * Created by SKR-CYW on 2016/10/20.
 */

public abstract class BaseActivity extends AppCompatActivity implements EasyPermissions.PermissionCallbacks {
    private static final int PERMISSION_REQUEST_CODE = 0x10;
    public static final String INTENT_FROM_MANUAL = "isFromManual";
    private static final String[] RUNTIME_PERMISSIONS = new String[]{
            "android.permission.WRITE_CONTACTS",
            "android.permission.GET_ACCOUNTS",
            "android.permission.READ_CONTACTS",
            "android.permission.READ_CALL_LOG",
            "android.permission.READ_PHONE_STATE",
            "android.permission.CALL_PHONE",
            "android.permission.WRITE_CALL_LOG",
            "android.permission.PROCESS_OUTGOING_CALLS",
            "android.permission.READ_CALENDAR",
            "android.permission.WRITE_CALENDAR",
            "android.permission.CAMERA",
            "android.permission.ACCESS_FINE_LOCATION",
            "android.permission.ACCESS_COARSE_LOCATION",
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE",
            "android.permission.RECORD_AUDIO",
            "android.permission.READ_SMS",
            "android.permission.RECEIVE_WAP_PUSH",
            "android.permission.RECEIVE_MMS",
            "android.permission.RECEIVE_SMS",
            "android.permission.SEND_SMS",
            "android.permission.READ_CELL_BROADCASTS"
            //            "android.permission.READ_CALENDAR",
//            "android.permission.WRITE_CALENDAR"
    };
    protected View mRootView;
    protected String fromWhere;
    protected Resources mResources;
    public static final String INTENT_FROM = "fromWhere";
    protected static final String FROM_NONE = "none";
    protected final String TAG = this.getClass().getSimpleName();
    protected Context mAppContext;
    protected Activity mActContext;
    @BindView(R2.id.toolbar)
    Toolbar mToolbar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate: " + this.getClass().getSimpleName());
        mAppContext = this.getApplicationContext();
        mActContext = this;
        ActivityHelper.getInstance().addActivity(this);
        fromWhere = getIntent().getStringExtra(INTENT_FROM);
        if (fromWhere == null) {
            fromWhere = FROM_NONE;
        }
        mResources = getResources();
        if (getLayoutId() == 0)
            return;
        setContentView();
        ButterKnife.bind(this);//必须在设置布局之后
        initToolsBar();
        initView();
    }

    protected boolean checkPermissions() {
        if (getTargetSdk() < M) {
            return true;
        }
        boolean hasPermissions = EasyPermissions.hasPermissions(this, RUNTIME_PERMISSIONS);
        Log.d(TAG, "checkPermissions: hasPermissions " + hasPermissions);
        if (hasPermissions) {
            return true;
        }
        EasyPermissions.requestPermissions(
                new PermissionRequest.Builder(this, PERMISSION_REQUEST_CODE, RUNTIME_PERMISSIONS)
                        .setRationale(getResources().getString(R.string.common_lack_permissions))
                        .setPositiveButtonText(R.string.common_sure)
                        .setNegativeButtonText(R.string.common_cancel)
                        .build());
        return false;
    }

    protected int getTargetSdk() {
        try {
            final PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 0);
            return info.applicationInfo.targetSdkVersion;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 1;
    }


    private void initToolsBar() {
        mToolbar = findViewById(R.id.toolbar);
        if (mToolbar == null) {
            return;
        }
        setSupportActionBar(mToolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolbar = findViewById(R.id.toolbar);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void setContentView() {
        mRootView = LayoutInflater.from(this).inflate(getLayoutId(), null);
        setContentView(mRootView);
    }

    public abstract int getLayoutId();

    public abstract void initView();


    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: " + this.getClass().getSimpleName());
        ActivityHelper.getInstance().removeActivity(this);
    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.d(TAG, "onNewIntent: " + this.getClass().getSimpleName());
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume: " + this.getClass().getSimpleName());
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause: " + this.getClass().getSimpleName());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "onActivityResult requestCode: " + requestCode);
        if (requestCode == AppSettingsDialog.DEFAULT_SETTINGS_REQ_CODE) {
            if (!EasyPermissions.hasPermissions(this, RUNTIME_PERMISSIONS)) {
                showPermissionDialog();
            }
        }
    }

    @Override
    public void onPermissionsGranted(int i, @NonNull List<String> perms) {
        Log.d(TAG, "onPermissionsGranted: ");
    }

    @Override
    public void onPermissionsDenied(int i, @NonNull List<String> perms) {
        if (perms != null && perms.size() > 0) {
            for (String perm : perms) {
                Log.d(TAG, "onPermissionsDenied: " + perm);
            }
        }
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            showPermissionDialog();
        }
    }

    private void showPermissionDialog() {
        new AppSettingsDialog.Builder(this)
                .setTitle(getResources().getString(R.string.common_remind))
                .setRationale(getResources().getString(R.string.common_lack_permissions))
                .build().show();
    }

    public void windowConfig(Activity activity) {
        Window window = activity.getWindow();
        WindowManager.LayoutParams windowLayoutParams = window.getAttributes();
        windowLayoutParams.width = 1;
        windowLayoutParams.height = 1;
        window.setAttributes(windowLayoutParams);
    }

    protected void transparent() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //5.x开始需要把颜色设置透明，否则导航栏会呈现系统默认的浅灰色
                Window window = this.getWindow();
                View decorView = window.getDecorView();
                //两个 flag 要结合使用，表示让应用的主体内容占用系统状态栏的空间
                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                decorView.setSystemUiVisibility(option);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
            } else {
                Window window = this.getWindow();
                WindowManager.LayoutParams attributes = window.getAttributes();
                int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
                attributes.flags |= flagTranslucentStatus;
                window.setAttributes(attributes);
            }
        }
    }
}
