package com.imtm1.starwarsgame;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Path;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public class MainActivity extends AppCompatActivity implements SensorEventListener{

    ImageView padExte;
    ImageView padCenter;
    ViewGroup mainLayout;
    ImageView asteroid1;
    ImageView asteroid2;
    ImageView asteroid3;
    ImageView tie;
    ImageView explosion;
    private SensorManager mSensorManager;
    private Sensor accelerometer;

    @SuppressLint("ClickableViewAccessibility")
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        padExte = findViewById(R.id.padExte);
        padCenter = findViewById(R.id.padCenter);
        mainLayout = (RelativeLayout) findViewById(R.id.main);
        asteroid1 = findViewById(R.id.asteroid1);
        asteroid2 = findViewById(R.id.asteroid2);
        explosion=findViewById(R.id.explosion);

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);

        float height = metrics.heightPixels;
        float width = metrics.widthPixels;
        RectF oval = new RectF(100,100, width-180, height/2);

        tie = findViewById(R.id.tie);

        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        // on recupere l accelerometre a partir du SensorManager
        accelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        // on associe l ecouteur d’evenements au SensorManager
        mSensorManager.registerListener((SensorEventListener) this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);


        Path arc1 = new Path();
        //path.arcTo(0f, 0f, 800f, 1200f, -270f, -180f, true);
        arc1.arcTo(oval,-80,180);
        ObjectAnimator animator = ObjectAnimator.ofFloat(asteroid1, View.X, View.Y, arc1);
        animator.setDuration(2000);
        animator.setRepeatCount(Animation.INFINITE);
        animator.setRepeatMode(ValueAnimator.REVERSE);
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                if(sontEnCollision(asteroid1,tie)){
                    Log.i("collision", "true");
                    explosion.setX(tie.getX());
                    explosion.setY(tie.getY());
                    showExplosion();
                }
            }
        });
        animator.start();

        Path line1 = new Path();
        //path2.arcTo(100f, 50f, width/4f,(3*height)/5, -150f, -190f, true);
        line1.lineTo((3*width)/4,(3*height)/5);
        ObjectAnimator animator2 = ObjectAnimator.ofFloat(asteroid2, View.X, View.Y, line1);
        animator2.setDuration(2400);
        animator2.setRepeatCount(Animation.INFINITE);
        animator2.setRepeatMode(ValueAnimator.REVERSE);
        animator2.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                if(sontEnCollision(asteroid2,tie)){
                    Log.i("collision2", "true");
                    explosion.setX(tie.getX());
                    explosion.setY(tie.getY());
                    showExplosion();
                }
            }
        });
        animator2.start();


        JoyStickView joyStickView = new JoyStickView(mainLayout,MainActivity.this,tie);

        Handler handlerForMovingTie = new Handler();
        Runnable movingTie = new Runnable() {
            @Override
            public void run() {
               // tie.setTranslationX(joyStickView.xDelta);
               // tie.setTranslationY(joyStickView.yDelta);

                Log.i( "TAG","Bool:"+ joyStickView.joystickIsPressed);
                if (joyStickView.joystickIsPressed) {
                    Toast.makeText(MainActivity.this, "joysitck is pressed", Toast.LENGTH_SHORT).show();
                    handlerForMovingTie.postDelayed(this, 10);
                    mainLayout.invalidate();

                }
            }
        };
        handlerForMovingTie.post(movingTie);
        Thread threadTie = new Thread(movingTie);
        threadTie.start();
        Log.i("TAG", "Thread:"+Thread.currentThread().getName());
        Log.i("tag", "Hello");
        padCenter.setOnTouchListener(joyStickView.touchListener);

    }

    private void showExplosion() {
        explosion.setVisibility(View.VISIBLE);

        explosion.postDelayed(new Runnable() {
            @Override
            public void run() {
                explosion.setVisibility(View.INVISIBLE);
            }
        }, 500); // produce 5 sec delay in button visibility
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {// TODO Auto−generated method stub
    }

    @Override
    public void onSensorChanged(SensorEvent event) {// TODO Auto−generated method stub
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int height = displayMetrics.heightPixels;
        int width = displayMetrics.widthPixels;
        float gammaX = event.values[0], gammaY = event.values[1], gammaZ = event.values[2];

        //move vaisseau
        tie.setX(tie.getX()-((gammaX)*4));
        tie.setY(tie.getY()+((gammaY)*4));

        if(tie.getX()<0){
            tie.setX(0);
        }else if(tie.getX()>=(width-tie.getWidth())){
            tie.setX(width-tie.getWidth());
        }
        if(tie.getY()<0){
            tie.setY(0);
        }else if(tie.getY()>=(height*0.6)){
            tie.setY((float) (height*0.6));
        }
    }

    boolean sontEnCollision(ImageView firstView, ImageView secondView) {
        int [] firstPosition = new int[2];

        int [] secondPosition = new int[2];
        firstView .getLocationOnScreen(firstPosition);
        secondView.getLocationOnScreen(secondPosition);


        Rect rectFirstView = new Rect(firstPosition [0], firstPosition [1],
                firstPosition [0] + firstView .getMeasuredWidth()/2, firstPosition [1] + firstView .getMeasuredHeight()/2);
        Rect rectSecondView = new Rect(secondPosition[0], secondPosition[1],
                secondPosition[0] + secondView.getMeasuredWidth(), secondPosition[1] + secondView.getMeasuredHeight());

        float x_inter = Math.max(0, Math.min(rectFirstView.right, rectSecondView.right) - Math.max(rectFirstView.left, rectSecondView.left));
        float y_inter = Math.max(0, Math.min(rectFirstView.bottom, rectSecondView.bottom) - Math.max(rectFirstView.top, rectSecondView.top));
        float aireInter = x_inter * y_inter;

        return(rectFirstView. intersect (rectSecondView));
    }
}
