package com.example.a8_bitinvader;

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Button;
import android.content.Context;
import android.media.AudioManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.media.MediaPlayer;
import android.content.Context;
import android.app.Dialog;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.text.SpannableStringBuilder;
import android.text.style.BulletSpan;
import android.text.Spanned;
public class MainActivity extends AppCompatActivity {
    Animation animation;
    int currentCharacter;
    int inputLives = 3;
    private MediaPlayer themeSound;
    private CharacterPagerAdapter characterPagerAdapter;
    private ViewPager characterViewPager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        /** initializes information about NDK */
        System.loadLibrary("native-lib");

        setContentView(R.layout.activity_main);

        /** Initialize the CharacterPagerAdapter */
        characterPagerAdapter = new CharacterPagerAdapter();
        characterViewPager = findViewById(R.id.characterViewPager);
        characterViewPager.setAdapter(characterPagerAdapter);

        /** Playing Background Music
         *  Music Download Link: https://hypeddit.com/track/njf8op
         */
        themeSound = MediaPlayer.create(this, R.raw.homeaudio);
        themeSound.start();

        /** the if statement below hides the action bar
         *  https://www.geeksforgeeks.org/different-ways-to-hide-action-bar-in-android-with-examples/
         */
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }

        /** Initializes 8-bit Invaders Logo */
        ImageView logo = (ImageView) findViewById(R.id.image_logo);
        logo.setImageResource(R.drawable.invaderslogo);

        /** Initializes Box to enter name */
        //EditText nameBox = findViewById(R.id.name_box);

        /** Creates new Intent and starts GameActivity if 'play' is pressed on MainActivity screen. */
        findViewById(R.id.play_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //String name = nameBox.getText().toString();

                /** pass number of player lives and player name to gameActivity */
                Intent intentStart = new Intent(MainActivity.this, GameActivity.class);
                intentStart.putExtra("inputLives", inputLives);
                //Intent intentLevel = new Intent(MainActivity.this, Level.class);
                //intentLevel.putExtra("playerName", name);
                Player.setSelectedCharacterIndex(characterViewPager.getCurrentItem());
                startActivity(intentStart);
            }
        });

        findViewById(R.id.help_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showHelpDialog();
            }
        });

        /** Creates new Intent and Mutes Device Audio if mute button is pressed on MainActivity screen
          * Reference: https://www.youtube.com/watch?v=_Klq62-me8s&ab_channel=AppleCoders
          * Reference: https://developer.android.com/reference/android/media/MediaPlayer */
        findViewById(R.id.mute_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                /** Declare an audio manager */
                AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
                /**
                  *A DJUST_MUTE => mutes the device
                  * FLAG_SHOW_UI => Show changes made to the volume bar
                  */
                audioManager.adjustVolume (AudioManager.ADJUST_MUTE, AudioManager.FLAG_SHOW_UI);
            }
        });


        /** Creates new Intent and stars LeaderboardView if the leaderboard button is pressed on the MainActivity Screen */
        findViewById(R.id.leaderboard_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showLeaderboardDialog();
            }
        });

        findViewById(R.id.lives1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputLives = 1;
            }
        });
        findViewById(R.id.lives3).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputLives = 3;
            }
        });
        findViewById(R.id.lives5).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                inputLives = 5;
            }
        });

        ImageView leftButton = findViewById(R.id.left_button);
        leftButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int currentPosition = characterViewPager.getCurrentItem();
                int maxPosition = characterPagerAdapter.getCount() - 1;
                if (currentPosition > 0) {
                    characterViewPager.setCurrentItem(currentPosition - 1);
                }
                else {
                    characterViewPager.setCurrentItem(maxPosition);
                }
            }
        });

        ImageView rightButton = findViewById(R.id.right_button);
        rightButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int currentPosition = characterViewPager.getCurrentItem();
                int maxPosition = characterPagerAdapter.getCount() - 1;
                if (currentPosition < maxPosition) {
                    characterViewPager.setCurrentItem(currentPosition + 1);
                }
                else {
                    characterViewPager.setCurrentItem(0);
                }
            }
        });

    }

    private class CharacterPagerAdapter extends PagerAdapter {
        private int[] characterImages = {R.drawable.player, R.drawable.player2, R.drawable.player3, R.drawable.player4};
        private int selectedCharacterIndex = 0;

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int position) {
            ImageView characterImageView = new ImageView(MainActivity.this);
            characterImageView.setImageResource(characterImages[position]);
            characterImageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            container.addView(characterImageView);
            return characterImageView;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((ImageView) object);
        }

        @Override
        public int getCount() {
            return characterImages.length;
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }

        /** Add a getter method to retrieve the selected character index */
        public int getSelectedCharacterIndex() {
            return selectedCharacterIndex;
        }
    }

    /**
     * Open up the popup window
     */
    private void showLeaderboardDialog() {

        ScoreFileWriter scoreFw = new ScoreFileWriter(this);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Leaderboard");
        String[] scores = scoreFw.getTopScores();

        StringBuilder messageBuilder = new StringBuilder();

        int i = 1;
        for (String score : scores) {

            if(score != null){
                messageBuilder.append(i + ") ").append(score).append("\n");
            }
            i++;
        }

        builder.setMessage(messageBuilder.toString());

        /** Add an "OK" button to close the dialog */
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss(); /** Close the dialog */
            }
        });

        /** Create and show the dialog */
        AlertDialog leaderboardDialog = builder.create();
        leaderboardDialog.show();
    }

    /**
     * Pop Up Window for Help Button
     */
    private void showHelpDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Game Instructions");
        String[] instructions = {
                "Choose your character using the left and right arrows on the Main Screen.",
                "Select the number of lives you want. The lower the lives, the higher the score multiplier!",
                "Use the joystick to move your character. Shoot down as many enemies as possible!",
                "Do not crash your spaceship and do not let enemies leave the screen!",
                "HAVE FUN!!"
        };

        StringBuilder messageBuilder = new StringBuilder();
        for (String instruction : instructions) {
            messageBuilder.append("\u2022 ").append(instruction).append("\n");
        }

        builder.setMessage(messageBuilder.toString());

        /** Add an "OK" button to close the dialog */
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss(); /** Close the dialog */
            }
        });

        /** Create and show the dialog */
        AlertDialog helpDialog = builder.create();
        helpDialog.show();
    }

    /** This function calls the android NDK to use c++ code */

    public native boolean isOffScreen(int yPos, int screenHeight);

    @Override
    protected void onStart() {
        super.onStart();
    }

    /**
     * Resume the game
     */
    @Override
    protected void onResume() {
        super.onResume();
    }

    /**
     * Pause the game
     */
    @Override
    protected void onPause() {
        super.onPause();
        themeSound.release();
        themeSound = null;
    }

    /**
     * Stop the game
     */
    @Override
    protected void onStop() {
        super.onStop();
    }

    /**
     * Destroy the sprite
     */
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    /**
     * Restart the game
     */
    @Override
    protected void onRestart() {
        super.onRestart();
    }

    @Override
    public void onBackPressed() {
        /** Call super.onBackPressed() to perform default back button behavior */
        super.onBackPressed();
    }
}