package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.StrictMode;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatSeekBar;
import androidx.appcompat.widget.Toolbar;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.MyCallback;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.MyContent;
import com.cygnusa.hyperm.wrappers.MyTopic;

import java.util.HashMap;

import retrofit2.Call;
import retrofit2.Response;


public class AudioViewActivity extends AppCompatActivity implements MediaPlayer.OnCompletionListener,
        MediaPlayer.OnBufferingUpdateListener {
    TextView contentTitle, contentDescription;
    public static MyContent CONTENT = new MyContent();
    public static MyTopic TOPIC = new MyTopic();
    ApiService restService;

    ImageButton toolPlayIcon, stopButton;
    AppBarLayout appBarLayout;
    Toolbar toolbar;
    FloatingActionButton playButton;
    CollapsingToolbarLayout collapsingToolbar;
    private MediaPlayer mediaPlayer;
    private int mediaFileLengthInMilliseconds;
    private Handler handler = new Handler();
    ProgressBar progressBar;
    private AppCompatSeekBar seekBar;
    TextView seekValue;
    private int mDurationSecondsMax = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_audio_view);
        setupWindowAnimations();
        restService = ((MainApplication) getApplication()).getClient();

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        contentTitle = findViewById(R.id.contentTitle);
        contentTitle.setText(CONTENT.getTitle());
        contentDescription = findViewById(R.id.contentDescription);
        contentDescription.setText(CONTENT.getDescription());
        contentDescription.setMovementMethod(new ScrollingMovementMethod());
        toolPlayIcon = findViewById(R.id.toolPlayIcon);
        appBarLayout = findViewById(R.id.appBarLayout);
        toolbar = findViewById(R.id.toolbar);
        seekBar = findViewById(R.id.seekBar);
        seekValue = findViewById(R.id.seekValue);
        stopButton = findViewById(R.id.stopButton);
        progressBar = findViewById(R.id.progressBar);
        progressBar.setVisibility(View.GONE);

        stopButton.setEnabled(false);
        seekBar.setEnabled(false);

        setSupportActionBar(toolbar);
        toolbar.setTitle("");
        getSupportActionBar().setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        @SuppressLint("PrivateResource")
        Drawable backArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_material);
        backArrow.setColorFilter(getResources().getColor(R.color.btn_bg_color), PorterDuff.Mode.SRC_ATOP);
        getSupportActionBar().setHomeAsUpIndicator(backArrow);

        collapsingToolbar = findViewById(R.id.collapsing_toolbar);

        appBarLayout.addOnOffsetChangedListener(new AppBarLayout.OnOffsetChangedListener() {
            @Override
            public void onOffsetChanged(AppBarLayout appBarLayout, int verticalOffset) {
                if (Math.abs(verticalOffset) - appBarLayout.getTotalScrollRange() == 0) {
                    toolbar.setBackgroundColor(Color.parseColor("#2f6aac"));
                    toolPlayIcon.setVisibility(View.VISIBLE);
                } else {
                    toolbar.setBackgroundColor(Color.TRANSPARENT);
                    toolPlayIcon.setVisibility(View.GONE);
                }
            }
        });

        playButton = findViewById(R.id.playButton);

        playButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
                    progressBar.setVisibility(View.VISIBLE);
                    playButton.setImageResource(R.mipmap.pause_icon);
                    toolPlayIcon.setImageResource(R.mipmap.pause_icon_white);
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            try {

                                mediaPlayer.setDataSource(CONTENT.getContent_files().get(0).getFile_url().trim());
                                mediaPlayer.prepare();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            mediaFileLengthInMilliseconds = mediaPlayer.getDuration();
                            seekBar.setMax(mediaFileLengthInMilliseconds / 1000);
                            mDurationSecondsMax = mediaFileLengthInMilliseconds / 1000;
                            seekValue.setText(secondsToTime(seekBar.getProgress()));

                            if (seekBar.getProgress() == 0 && !CONTENT.getStatus().trim().equalsIgnoreCase("1")
                                    && !CONTENT.getStatus().trim().equalsIgnoreCase("2")) {
                                updateStatus("1");
                            }
                            seekBar.setEnabled(true);
                            stopButton.setEnabled(true);
                            mediaPlayer.start();
                            progressBar.setVisibility(View.GONE);
                            primarySeekBarProgressUpdater();
                        }
                    });
                } else {
                    mediaPlayer.pause();
                    playButton.setImageResource(R.mipmap.play_icon);
                    toolPlayIcon.setImageResource(R.mipmap.play_icon_white);
                    primarySeekBarProgressUpdater();
                }
            }
        });
        Log.e("ee",CONTENT.getContent_files().get(0).getFile_url().trim());

        toolPlayIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
                    progressBar.setVisibility(View.VISIBLE);
                    playButton.setImageResource(R.mipmap.pause_icon);
                    toolPlayIcon.setImageResource(R.mipmap.pause_icon_white);
                    new Handler().post(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                mediaPlayer.setDataSource(CONTENT.getContent_files().get(0).getFile_url().trim());
                                mediaPlayer.prepare();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            mediaFileLengthInMilliseconds = mediaPlayer.getDuration();
                            seekBar.setMax(mediaFileLengthInMilliseconds / 1000);
                            mDurationSecondsMax = mediaFileLengthInMilliseconds / 1000;
                            seekValue.setText(secondsToTime(seekBar.getProgress()));

                            if (seekBar.getProgress() == 0 && !CONTENT.getStatus().trim().equalsIgnoreCase("1")
                                    && !CONTENT.getStatus().trim().equalsIgnoreCase("2")) {
                                updateStatus("1");
                            }
                            seekBar.setEnabled(true);
                            stopButton.setEnabled(true);
                            mediaPlayer.start();
                            progressBar.setVisibility(View.GONE);
                            primarySeekBarProgressUpdater();
                        }
                    });
                } else {
                    mediaPlayer.pause();
                    playButton.setImageResource(R.mipmap.play_icon);
                    toolPlayIcon.setImageResource(R.mipmap.play_icon_white);
                    primarySeekBarProgressUpdater();
                }
            }
        });

        collapsingToolbar.setTitle(TOPIC.getTopicname());

        mediaPlayer = new MediaPlayer();
        mediaPlayer.setOnBufferingUpdateListener(this);
        mediaPlayer.setOnCompletionListener(this);

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                seekValue.setText(secondsToTime(progress));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (mediaPlayer.isPlaying()) {
                    int playPositionInMillisecconds = seekBar.getProgress() * 1000;
                    mediaPlayer.seekTo(playPositionInMillisecconds);
                }
            }
        });

        stopButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    mediaPlayer.stop();
                    mediaPlayer.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                handler.removeCallbacksAndMessages(null);
                seekBar.setProgress(0);
                seekBar.setEnabled(false);
                stopButton.setEnabled(false);
                playButton.setImageResource(R.mipmap.play_icon);
                toolPlayIcon.setImageResource(R.mipmap.play_icon_white);
                seekValue.setText("00:00/00:00");
                mediaPlayer = new MediaPlayer();
            }
        });
    }

    private void primarySeekBarProgressUpdater() {
        try {
            seekBar.setProgress(mediaPlayer.getCurrentPosition() / 1000);
            if (mediaPlayer.isPlaying()) {
                Runnable notification = new Runnable() {
                    public void run() {
                        primarySeekBarProgressUpdater();
                    }
                };
                handler.postDelayed(notification, 1000);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String secondsToTime(int seconds) {
        String time;

        String minutesText = String.valueOf(seconds / 60);
        if (minutesText.length() == 1)
            minutesText = "0" + minutesText;

        String secondsText = String.valueOf(seconds % 60);
        if (secondsText.length() == 1)
            secondsText = "0" + secondsText;

        String time1 = "";

        String minutesText1 = String.valueOf(mDurationSecondsMax / 60);
        if (minutesText1.length() == 1)
            minutesText1 = "0" + minutesText1;

        String secondsText1 = String.valueOf(mDurationSecondsMax % 60);
        if (secondsText1.length() == 1)
            secondsText1 = "0" + secondsText1;

        time = minutesText + ":" + secondsText + "/" + minutesText1 + ":" + secondsText1;

        return time;
    }

    private void setupWindowAnimations() {
        this.overridePendingTransition(R.anim.animation_enter,
                R.anim.animation_leave);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            finish();
            this.overridePendingTransition(R.anim.animation_f_enter,
                    R.anim.animation_f_leave);
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
        this.overridePendingTransition(R.anim.animation_f_enter,
                R.anim.animation_f_leave);
    }

    private void updateStatus(String status) {
        CONTENT.setStatus(status);
        if (new UtilService().isNetworkAvailable(AudioViewActivity.this)) {
            try {
                HashMap<String, String> map = new HashMap<>();
                map.put("contentid", CONTENT.getContentid());
                map.put("assettopicid", CONTENT.getAssettopicid());
                map.put("status", status);

                restService.updateContentStaus(map).enqueue(new MyCallback<ErrorResponse>(status) {
                    @Override
                    public void onResponse(Call<ErrorResponse> call, Response<ErrorResponse> response) {
                        if (response.body() != null && response.body().getStatus() == 200) {
                            CONTENT.setStatus(ids);
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            finish();
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                            GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                finish();
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ErrorResponse> call, Throwable t) {

                    }
                });

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (GlobalData.canLogout) {
            finish();
        }
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        seekBar.setSecondaryProgress(percent);
    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        if (!CONTENT.getStatus().trim().equalsIgnoreCase("2")) {
            updateStatus("2");
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            playButton.performClick();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
        }
    }

}