package com.efounder.chat.fragment;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import androidx.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.efounder.frame.baseui.BaseFragment;
import com.efounder.chat.R;
import com.efounder.frame.activity.EFTransformFragmentActivity;
import com.efounder.frame.baseui.EFFragment;
import com.efounder.frame.utils.EFAppAccountUtils;
import com.efounder.frame.utils.EFFrameUtils;
import com.efounder.utils.ResStringUtil;

/**
 * Created by Will on 2016/11/16.
 */

public class ShakeToFindFragment extends EFFragment {

    private ImageView up;
    private ImageView down;
    private LinearLayout loadingLayout;
    private RelativeLayout resultLayout;
    private RelativeLayout rlBack;
    private Button btSettings;
    private SensorManager sensorManager;
    private Sensor sensor;
    private Vibrator vibrator;
    private SoundPool soundPool;
    private int sound1;
    private long lastTime;
    private float[] gravity = new float[3];
    private float[] linear_acceleration = new float[3];
    private View view;

    /**
     * 加速度改变监听
     */
    SensorEventListener listener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {
            // alpha is calculated as t / (t + dT)
            // with t, the low-pass filter's time-constant
            // and dT, the event delivery rate

            final float alpha = 0.8f;
            gravity[0] = alpha * gravity[0] + (1 - alpha) * event.values[0];
            gravity[1] = alpha * gravity[1] + (1 - alpha) * event.values[1];
            gravity[2] = alpha * gravity[2] + (1 - alpha) * event.values[2];

            linear_acceleration[0] = Math.abs(event.values[0] - gravity[0]);
            linear_acceleration[1] = Math.abs(event.values[1] - gravity[1]);
            linear_acceleration[2] = Math.abs(event.values[2] - gravity[2]);
//            Log.d("linear_acce",linear_acceleration[0]+","+linear_acceleration[1]+","+linear_acceleration[2]+"");

            if (linear_acceleration[0]>15||linear_acceleration[1]>15||linear_acceleration[2]>15){
                if (resultLayout.getVisibility()== View.VISIBLE){
                    startResultGoneAnimation();
                }
                startAnimation();
            }
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };
    SensorEventListener gListener = new SensorEventListener() {
        @Override
        public void onSensorChanged(SensorEvent event) {

            gravity[0] = event.values[0];
            gravity[1] = event.values[1];
            gravity[2] = event.values[2];
        }

        @Override
        public void onAccuracyChanged(Sensor sensor, int accuracy) {

        }
    };


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_shake_to_find,container,false);
        up = (ImageView) view.findViewById(R.id.up);
        down = (ImageView) view.findViewById(R.id.down);
        resultLayout = (RelativeLayout) view.findViewById(R.id.shake_result_layout);
        loadingLayout = (LinearLayout) view.findViewById(R.id.shake_loading);
        rlBack = (RelativeLayout) view.findViewById(R.id.rl_back);
        rlBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getActivity().finish();
            }
        });
        btSettings = (Button) view.findViewById(R.id.button_settings);
        btSettings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    Bundle bundle = new Bundle();
                    bundle.putInt("id", EFAppAccountUtils.getAppAccountID());
                    bundle.putString(EFTransformFragmentActivity.EXTRA_TITLE_NAME,ResStringUtil.getString(R.string.wechatview_snake_set));
                    bundle.putInt(EFTransformFragmentActivity.EXTRA_TITLE_RIGHT_VISIBILITY,View.INVISIBLE);
                    EFFrameUtils.pushFragment((Class<? extends BaseFragment>) Class.forName("com.efounder.chat.fragment.ShakeSettingsFragment"),bundle);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
            }
        });
        initSensor();
        initSoundPool();
        vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
        setLoadingVisibility(false);
        setResultVisibility(false);
        return view;
    }

    /**
     * 初始化传感器
     */
    private void initSensor(){
        sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
        sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        sensorManager.registerListener(listener,sensor, SensorManager.SENSOR_DELAY_GAME);
        Sensor gSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
        sensorManager.registerListener(gListener,gSensor, SensorManager.SENSOR_DELAY_GAME);
    }


    /**
     * 初始化音频
     */
    private void initSoundPool(){
        if (Build.VERSION.SDK_INT > 20){
            SoundPool.Builder builder = new SoundPool.Builder();
            builder.setMaxStreams(3);
            AudioAttributes.Builder aaBuilder = new AudioAttributes.Builder();
            aaBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
            builder.setAudioAttributes(aaBuilder.build());
            soundPool = builder.build();
        }else {
            soundPool = new SoundPool(3, AudioManager.STREAM_MUSIC,0);
        }
        sound1 = soundPool.load(getActivity(),R.raw.shaking,1);
    }

    /**
     * 播放音频及震动
     */
    private void playSound(){
        soundPool.play(sound1,1,1,0,0,1);
        vibrator.vibrate(new long[]{100,200,100},-1);
    }

    /**
     * 开始摇一摇动画
     */
    private void startAnimation(){

        long currentTimeMillis = System.currentTimeMillis();
        if (currentTimeMillis - lastTime < 3000){
            return;
        }
        lastTime = currentTimeMillis;
        AnimationSet upSet = new AnimationSet(true);
        TranslateAnimation upUp = new TranslateAnimation(TranslateAnimation.RELATIVE_TO_SELF,0, TranslateAnimation.RELATIVE_TO_SELF,0,
                TranslateAnimation.RELATIVE_TO_SELF,0, TranslateAnimation.RELATIVE_TO_SELF,-1);
        upUp.setDuration(1000);
        TranslateAnimation upDown = new TranslateAnimation(TranslateAnimation.RELATIVE_TO_SELF,0, TranslateAnimation.RELATIVE_TO_SELF,0,
                TranslateAnimation.RELATIVE_TO_SELF,0, TranslateAnimation.RELATIVE_TO_SELF,1);
        upDown.setDuration(1000);
        upDown.setStartOffset(1000);
        upSet.addAnimation(upUp);
        upSet.addAnimation(upDown);
        up.startAnimation(upSet);
        upSet.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                //弹出结果
                setLoadingVisibility(true);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        setLoadingVisibility(false);
                        startResultAnimation();
                    }
                },1000);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });

        AnimationSet downSet = new AnimationSet(true);
        TranslateAnimation downUp = new TranslateAnimation(TranslateAnimation.RELATIVE_TO_SELF,0, TranslateAnimation.RELATIVE_TO_SELF,0,
                TranslateAnimation.RELATIVE_TO_SELF,0, TranslateAnimation.RELATIVE_TO_SELF,1);
        downUp.setDuration(1000);
        TranslateAnimation downDown = new TranslateAnimation(TranslateAnimation.RELATIVE_TO_SELF,0, TranslateAnimation.RELATIVE_TO_SELF,0,
                TranslateAnimation.RELATIVE_TO_SELF,0, TranslateAnimation.RELATIVE_TO_SELF,-1);
        downDown.setDuration(1000);
        downDown.setStartOffset(1000);
        downSet.addAnimation(downUp);
        downSet.addAnimation(downDown);
        down.startAnimation(downSet);
        playSound();
    }

    /**
     * 开始结果显示动画
     */
    private void startResultAnimation(){
        TranslateAnimation animation = new TranslateAnimation(TranslateAnimation.RELATIVE_TO_SELF,0, TranslateAnimation.RELATIVE_TO_SELF,0,
                TranslateAnimation.RELATIVE_TO_SELF,-1.2f, TranslateAnimation.RELATIVE_TO_SELF,0);
        animation.setDuration(400);
        setResultVisibility(true);
        resultLayout.startAnimation(animation);

    }

    private void startResultGoneAnimation(){
        TranslateAnimation animation = new TranslateAnimation(TranslateAnimation.RELATIVE_TO_SELF,0, TranslateAnimation.RELATIVE_TO_SELF,0,
                TranslateAnimation.RELATIVE_TO_SELF,0, TranslateAnimation.RELATIVE_TO_SELF,3);
        animation.setDuration(400);
        resultLayout.startAnimation(animation);
        setResultVisibility(false);
    }

    /**
     * 显示结果控制
     * @param isVisible
     */
    private void setResultVisibility(boolean isVisible){
        if (isVisible){
            resultLayout.setVisibility(View.VISIBLE);
        }else{
            resultLayout.setVisibility(View.INVISIBLE);
        }
    }

    /**
     * 加载信息控制
     * @param isVisible
     */
    private void setLoadingVisibility(boolean isVisible){
        if (isVisible){
            loadingLayout.setVisibility(View.VISIBLE);
        }else {
            loadingLayout.setVisibility(View.INVISIBLE);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (listener!=null){
            sensorManager.unregisterListener(listener);
        }
        if (soundPool!=null){
            soundPool.release();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (listener!=null){
            sensorManager.unregisterListener(listener);
        }
//        if (soundPool!=null){
//            soundPool.release();
//        }
    }

    @Override
    public void onResume() {
        super.onResume();
        initSensor();
    }
}
