package com.example.shorti;

import android.content.Context;
import android.content.SharedPreferences;
import android.media.Image;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Part;
import retrofit2.http.Path;

public class MainFeed extends AppCompatActivity {
    Button prev;
    Button next;
    Button playStop;
    SharedPreferences settings;
    VideoView mainplayer;
    List<Short> shorts;
    int cur_idx;
    ImageView imageView2;
    TextView username;
    TextView likes;

    interface RequestShorts {
        @GET("/api/Shorts?page=1&count=1000")
        Call<List<Short>> getAllShorts(@Header("Authorization") String auth_header_value);
    }

    interface RequestUser {
        @GET("/api/Users/{userId}")
        Call<ResponseUser> getUser(@Path("userId") String userId, @Header("Authorization") String auth_header_value);
    }

    interface RequestActivities {
        @GET("/api/Activities/count-likes/{shortId}")
        Call<String> getLikes(@Path("shortId") String shortId, @Header("Authorization") String auth_header_value);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main_feed);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        prev = findViewById(R.id.prev);
        next = findViewById(R.id.next);
        playStop = findViewById(R.id.playstop);
        mainplayer = findViewById(R.id.mainplayer);
        imageView2 = findViewById(R.id.imageView2);
        username = findViewById(R.id.username);
        likes = findViewById(R.id.likes);
        cur_idx = 0;

        imageView2.setImageURI(Uri.parse("http://212.109.198.242:5171/avatars/a8fa19b5-2f53-47ab-8ebf-e6c7e1547fe2.jpg"));

        Context context = (Context) this;

        settings = getSharedPreferences("user_data", MODE_PRIVATE);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://212.109.198.242:5171")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        RequestUser requestUser = retrofit.create(RequestUser.class);
        RequestActivities requestActivities = retrofit.create(RequestActivities.class);

        RequestShorts requestShorts = retrofit.create(RequestShorts.class);
        requestShorts.getAllShorts("Bearer " + settings.getString("access_token", "")).enqueue(new Callback<List<Short>>() {
            @Override
            public void onResponse(Call<List<Short>> call, Response<List<Short>> response) {
                //Toast.makeText(context, "size: " + response.body().size(), Toast.LENGTH_SHORT).show();
                Toast.makeText(context, response.code() + "success " + response.isSuccessful(), Toast.LENGTH_LONG).show();
                if (response.isSuccessful()) {
                    shorts = response.body();
                    requestActivities.getLikes(shorts.get(0).id, "Bearer " + settings.getString("access_token", "")).enqueue(new Callback<String>() {
                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                            //Toast.makeText(context, response.body().toString(), Toast.LENGTH_LONG).show();
                            if (response.isSuccessful()) {
                                likes.setText(response.body().toString());
                            }
                        }

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {
                            Toast.makeText(context, "активность ошибка", Toast.LENGTH_LONG).show();
                        }
                    });
                    requestUser.getUser(shorts.get(0).authorId, "Bearer " + settings.getString("access_token", "")).enqueue(new Callback<ResponseUser>() {
                        @Override
                        public void onResponse(Call<ResponseUser> call, Response<ResponseUser> response) {
                            if (response.isSuccessful()) {
                                username.setText(response.body().userName);
                                ImageManager.fetchImage("http://212.109.198.242:5171/"+response.body().avatarPath, imageView2);
                            } else {
                                Toast.makeText(context, response.code(), Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseUser> call, Throwable t) {
                            Toast.makeText(context, "ошибка юзера", Toast.LENGTH_SHORT).show();
                        }
                    });
                    mainplayer.setVideoPath("http://212.109.198.242:5171/" + shorts.get(0).fileName);
                    mainplayer.start();
                }
            }



            @Override
            public void onFailure(Call<List<Short>> call, Throwable t) {
                Toast.makeText(context, "ошибка", Toast.LENGTH_SHORT).show();
            }
        });

        prev.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (cur_idx > 0) {
                    requestActivities.getLikes(shorts.get(cur_idx).id, "Bearer " + settings.getString("access_token", "")).enqueue(new Callback<String>() {
                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                            //Toast.makeText(context, response.body().toString(), Toast.LENGTH_LONG).show();
                            if (response.isSuccessful()) {
                                likes.setText(response.body().toString());
                            }
                        }

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {
                            Toast.makeText(context, "активность ошибка", Toast.LENGTH_LONG).show();
                        }
                    });
                    requestUser.getUser(shorts.get(cur_idx).authorId, "Bearer " + settings.getString("access_token", "")).enqueue(new Callback<ResponseUser>() {
                        @Override
                        public void onResponse(Call<ResponseUser> call, Response<ResponseUser> response) {
                            if (response.isSuccessful()) {
                                username.setText(response.body().userName);
                                //Toast.makeText(context, response.code() + "user", Toast.LENGTH_SHORT).show();
                                ImageManager.fetchImage("http://212.109.198.242:5171/"+response.body().avatarPath, imageView2);
                            } else {
                                Toast.makeText(context, response.code(), Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseUser> call, Throwable t) {
                            Toast.makeText(context, "ошибка юзера", Toast.LENGTH_SHORT).show();
                        }
                    });
                    mainplayer.setVideoPath("http://212.109.198.242:5171/" + shorts.get(--cur_idx).fileName);
                }
            }
        });

        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (++cur_idx < shorts.size()) {
                    requestActivities.getLikes(shorts.get(cur_idx).id, "Bearer " + settings.getString("access_token", "")).enqueue(new Callback<String>() {
                        @Override
                        public void onResponse(Call<String> call, Response<String> response) {
                            //Toast.makeText(context, response.body().toString(), Toast.LENGTH_LONG).show();
                            if (response.isSuccessful()) {
                                likes.setText(response.body().toString());
                            }
                        }

                        @Override
                        public void onFailure(Call<String> call, Throwable t) {
                            Toast.makeText(context, "активность ошибка", Toast.LENGTH_LONG).show();
                        }
                    });
                    requestUser.getUser(shorts.get(cur_idx).authorId, "Bearer " + settings.getString("access_token", "")).enqueue(new Callback<ResponseUser>() {
                        @Override
                        public void onResponse(Call<ResponseUser> call, Response<ResponseUser> response) {
                            if (response.isSuccessful()) {
                                username.setText(response.body().userName);
                                //Toast.makeText(context, response.code() + "user", Toast.LENGTH_SHORT).show();
                                ImageManager.fetchImage("http://212.109.198.242:5171/"+response.body().avatarPath, imageView2);
                            } else {
                                Toast.makeText(context, response.code(), Toast.LENGTH_SHORT).show();
                            }
                        }

                        @Override
                        public void onFailure(Call<ResponseUser> call, Throwable t) {
                            Toast.makeText(context, "ошибка юзера", Toast.LENGTH_SHORT).show();
                        }
                    });
                    mainplayer.setVideoPath("http://212.109.198.242:5171/" + shorts.get(cur_idx).fileName);
                }
            }
        });

        playStop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (playStop.getText().toString() == "Continue") {
                    mainplayer.start();
                    playStop.setText("Stop");
                } else {
                    mainplayer.pause();
                    playStop.setText("Continue");
                }
            }
        });
    }
}



// eyJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAxLzA0L3htbGRzaWctbW9yZSNobWFjLXNoYTI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI0NzFiMGZmYi1hOWJiLTRlMmMtYTc4ZS05NDkwNjgzMGU2NDgiLCJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiMTIzNDU2NyIsImh0dHA6Ly9zY2hlbWFzLnhtbHNvYXAub3JnL3dzLzIwMDUvMDUvaWRlbnRpdHkvY2xhaW1zL25hbWVpZGVudGlmaWVyIjoiYWFjZGZjMjgtMTUwNS00MjBmLTkxMGEtYTAwODdkY2FkZWEzIiwiZXhwIjoxNzEwNTMxNzYxLCJpc3MiOiJodHRwOi8vbG9jYWxob3N0OjUwNjQiLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0OjUyODMifQ._4nzOTi3oOoOl2TbqRhZ8ibPTyXaK5IW9TDNtjgmUPU