package com.yidianling.user.mine;

import android.annotation.TargetApi;
import android.app.AppOpsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.net.Uri;
import android.os.Build;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.ydl.ydlcommon.base.BaseActivity;
import com.ydl.ydlcommon.bean.StatusBarOptions;
import com.ydl.ydlcommon.data.PlatformDataManager;
import com.ydl.ydlcommon.modular.ModularServiceManager;
import com.yidianling.im.api.service.IImService;
import com.yidianling.user.R;

import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


/**
 * Created by Wi1ls on 2016/10/28;
 */
@Route(path = "/user/notifysetting")
public class NotificationsSettingActivity extends BaseActivity {
    TextView tv_isopen;
    ToggleButton tb_voice;
    ToggleButton tb_shake;


    @Override
    protected int layoutResId() {
        return R.layout.user_mine_activity_notifications_setting;
    }

    @NotNull
    @Override
    public StatusBarOptions getStatusViewOptions() {
        return new StatusBarOptions(true,true);
    }

    @Override
    protected void initDataAndEvent() {
        tv_isopen = findViewById(R.id.tv_isopen);
        tb_voice = findViewById(R.id.tb_voice);
        tb_shake = findViewById(R.id.tb_shake);
        init();
    }


    void init() {
        a();
        tb_voice.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                //设置声音开关
//                LogoutHelper.getInstance().saveVoice(isChecked);
                PlatformDataManager.INSTANCE.getLocal().putVoice(isChecked);
                try {
                    ModularServiceManager.INSTANCE.provide(IImService.class).imInSetRing(isChecked);
                } catch (Exception e) {}
//                JPushManager.INSTANCE.updateConfig(getApplicationContext());
            }
        });


        tb_shake.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                //设置震动开关
//                LogoutHelper.getInstance().saveShake(isChecked);
                PlatformDataManager.INSTANCE.getLocal().putShake(isChecked);
                try {
                    ModularServiceManager.INSTANCE.provide(IImService.class).imInSetVibrate(isChecked);
                } catch (Exception e) {}
//                JPushManager.INSTANCE.updateConfig(getApplicationContext());
            }
        });

        tv_isopen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getAppDetailSettingIntent(NotificationsSettingActivity.this);
            }
        });
    }


    private void a() {
        if (isNotificationEnabled(this)) {
            tv_isopen.setText("已开启");
            tb_voice.setClickable(true);
            tb_shake.setClickable(true);
            if (PlatformDataManager.INSTANCE.getLocal().isVoice()) {
                tb_voice.setChecked(true);
            } else {
                tb_voice.setChecked(false);
            }
            if (PlatformDataManager.INSTANCE.getLocal().isShake()) {
                tb_shake.setChecked(true);
            } else {
                tb_shake.setChecked(false);
            }
        } else {
            tv_isopen.setText("未开启");
            tb_voice.setChecked(false);
            tb_voice.setClickable(false);

            tb_shake.setChecked(false);
            tb_shake.setClickable(false);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        a();
    }

    private static final String CHECK_OP_NO_THROW = "checkOpNoThrow";
    private static final String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";

    @TargetApi(Build.VERSION_CODES.KITKAT)
    private boolean isNotificationEnabled(Context context) {

        AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);

        ApplicationInfo appInfo = context.getApplicationInfo();

        String pkg = context.getApplicationContext().getPackageName();

        int uid = appInfo.uid;

        Class appOpsClass = null; /* Context.APP_OPS_MANAGER */

        try {

            appOpsClass = Class.forName(AppOpsManager.class.getName());

            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE, String.class);

            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);
            int value = (int) opPostNotificationValue.get(Integer.class);

            return ((int) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }

    private void getAppDetailSettingIntent(Context context) {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= 9) {
            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
            localIntent.setData(Uri.fromParts("package", getPackageName(), null));
        } else if (Build.VERSION.SDK_INT <= 8) {
            localIntent.setAction(Intent.ACTION_VIEW);
            localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
            localIntent.putExtra("com.android.settings.ApplicationPkgName", getPackageName());
        }
        startActivity(localIntent);
    }

}
