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.view.animation.PathInterpolator;
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 asteroid4;
    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);
        asteroid3 = findViewById(R.id.asteroid3);
        asteroid4 = findViewById(R.id.asteroid4);
        explosion=findViewById(R.id.explosion);

        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        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


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

        tie = findViewById(R.id.tie);



        Path arc1 = new Path();

        arc1.arcTo(oval,-80,180);
        ObjectAnimator animator = ObjectAnimator.ofFloat(asteroid1, View.X, View.Y, arc1);
        animator.setDuration(3050);
        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();
        line1.lineTo((3*width)/4,(3*height)/5);
        ObjectAnimator animator2 = ObjectAnimator.ofFloat(asteroid2, View.X, View.Y, line1);
        animator2.setDuration(2350);
        animator2.setRepeatCount(Animation.INFINITE);
        animator2.setRepeatMode(ValueAnimator.REVERSE);
        animator2.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation2) {
                if(sontEnCollision(asteroid2,tie)){
                    Log.i("collision2", "true");
                    explosion.setX(tie.getX());
                    explosion.setY(tie.getY());
                    showExplosion();
                }
            }
        });
        animator2.start();

        Path arc2 = new Path();
        arc2.arcTo(100f, 50f, width/3f,(3*height)/5, 300f, -200f, true);
        ObjectAnimator animator3 = ObjectAnimator.ofFloat(asteroid3, View.X, View.Y, arc2);
        animator3.setDuration(2500);
        animator3.setRepeatCount(Animation.INFINITE);
        animator3.setRepeatMode(ValueAnimator.REVERSE);
        animator3.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation3) {
                if(sontEnCollision(asteroid3,tie)){
                    Log.i("collision2", "true");
                    explosion.setX(tie.getX());
                    explosion.setY(tie.getY());
                    showExplosion();
                }
            }
        });
        animator3.start();

        Path ovalPath = new Path();
        RectF oval2 = new RectF(10,(height)/5, (2*width)/3, (2*height)/5);
        ovalPath.addOval(oval2, Path.Direction.CW);
        ObjectAnimator animator4 = ObjectAnimator.ofFloat(asteroid4, View.X, View.Y, ovalPath);
        animator4.setupStartValues();
        animator4.setDuration(3200);
        animator4.setRepeatCount(Animation.INFINITE);
        animator4.setRepeatMode(ValueAnimator.REVERSE);
        animator4.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation4) {
                if(sontEnCollision(asteroid4,tie)){
                    Log.i("collision2", "true");
                    explosion.setX(tie.getX());
                    explosion.setY(tie.getY());
                    showExplosion();
                }
            }
        });
        animator4.start();

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

        Handler handlerForMovingTie = new Handler();
        Runnable movingTieJoystick = new Runnable() {
            @Override
            public void run() {

                padCenter.setOnTouchListener(joyStickView.touchListener);
            }
        };
        Thread threadTie = new Thread(movingTieJoystick);
        threadTie.start();


        Runnable movingTieSensor = new Runnable() {
            @Override
            public void run() {

                mSensorManager.registerListener((SensorEventListener)MainActivity.this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
            }
        };

        Thread threadTieSensor = new Thread(movingTieSensor);
        threadTieSensor.start();
    }

    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));
    }
}
