package app.fedilab.fedilabtube;
/* Copyright 2020 Thomas Schneider
 *
 * This file is a part of TubeLab
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the
 * GNU General Public License as published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * TubeLab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with TubeLab; if not,
 * see <http://www.gnu.org/licenses>. */

import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import java.util.ArrayList;
import java.util.List;

import app.fedilab.fedilabtube.client.APIResponse;
import app.fedilab.fedilabtube.client.data.PlaylistData.Playlist;
import app.fedilab.fedilabtube.client.data.VideoData.Video;
import app.fedilab.fedilabtube.client.data.VideoPlaylistData;
import app.fedilab.fedilabtube.drawer.PeertubeAdapter;
import app.fedilab.fedilabtube.viewmodel.PlaylistsVM;
import es.dmoral.toasty.Toasty;

import static app.fedilab.fedilabtube.viewmodel.PlaylistsVM.action.GET_LIST_VIDEOS;


public class PlaylistsActivity extends AppCompatActivity {


    LinearLayoutManager mLayoutManager;
    private RelativeLayout mainLoader, nextElementLoader, textviewNoAction;
    private SwipeRefreshLayout swipeRefreshLayout;
    private boolean swiped;
    private List<Video> peertubes;
    private String max_id;
    private Playlist playlist;
    private boolean firstLoad;
    private boolean flag_loading;
    private PeertubeAdapter peertubeAdapter;
    private PlaylistsVM viewModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if (getSupportActionBar() != null)
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);


        setContentView(R.layout.activity_playlists);
        peertubes = new ArrayList<>();

        RecyclerView lv_playlist = findViewById(R.id.lv_playlist);
        mainLoader = findViewById(R.id.loader);
        nextElementLoader = findViewById(R.id.loading_next_status);
        textviewNoAction = findViewById(R.id.no_action);
        mainLoader.setVisibility(View.VISIBLE);
        swipeRefreshLayout = findViewById(R.id.swipeContainer);


        max_id = null;
        flag_loading = true;
        firstLoad = true;
        swiped = false;


        mainLoader.setVisibility(View.VISIBLE);
        nextElementLoader.setVisibility(View.GONE);

        peertubeAdapter = new PeertubeAdapter(this.peertubes);

        lv_playlist.setAdapter(peertubeAdapter);
        mLayoutManager = new LinearLayoutManager(PlaylistsActivity.this);
        lv_playlist.setLayoutManager(mLayoutManager);

        Bundle b = getIntent().getExtras();
        if (b != null) {
            playlist = b.getParcelable("playlist");
        } else {
            Toasty.error(PlaylistsActivity.this, getString(R.string.toast_error), Toast.LENGTH_LONG).show();
            return;
        }
        if (getSupportActionBar() != null)
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        setTitle(playlist.getDisplayName());

        viewModel = new ViewModelProvider(PlaylistsActivity.this).get(PlaylistsVM.class);
        lv_playlist.addOnScrollListener(new RecyclerView.OnScrollListener() {
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                int firstVisibleItem = mLayoutManager.findFirstVisibleItemPosition();
                if (dy > 0) {
                    int visibleItemCount = mLayoutManager.getChildCount();
                    int totalItemCount = mLayoutManager.getItemCount();
                    if (firstVisibleItem + visibleItemCount == totalItemCount) {
                        if (!flag_loading) {
                            flag_loading = true;
                            viewModel.manage(GET_LIST_VIDEOS, playlist, null).observe(PlaylistsActivity.this, apiResponse -> manageVIewPlaylists(PlaylistsVM.action.GET_LIST_VIDEOS, apiResponse));
                            nextElementLoader.setVisibility(View.VISIBLE);
                        }
                    } else {
                        nextElementLoader.setVisibility(View.GONE);
                    }
                }
            }
        });


        swipeRefreshLayout.setOnRefreshListener(() -> {
            max_id = null;
            firstLoad = true;
            flag_loading = true;
            swiped = true;
            viewModel.manage(GET_LIST_VIDEOS, playlist, null).observe(PlaylistsActivity.this, apiResponse -> manageVIewPlaylists(PlaylistsVM.action.GET_LIST_VIDEOS, apiResponse));
        });
        viewModel.manage(GET_LIST_VIDEOS, playlist, null).observe(PlaylistsActivity.this, apiResponse -> manageVIewPlaylists(PlaylistsVM.action.GET_LIST_VIDEOS, apiResponse));
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    public void manageVIewPlaylists(PlaylistsVM.action actionType, APIResponse apiResponse) {
        mainLoader.setVisibility(View.GONE);
        nextElementLoader.setVisibility(View.GONE);
        if (apiResponse.getError() != null) {
            Toasty.error(PlaylistsActivity.this, apiResponse.getError().getError(), Toast.LENGTH_LONG).show();
            swipeRefreshLayout.setRefreshing(false);
            swiped = false;
            flag_loading = false;
            return;
        }
        if (actionType == GET_LIST_VIDEOS) {

            int previousPosition = this.peertubes.size();
            List<VideoPlaylistData.VideoPlaylist> videoPlaylists = apiResponse.getVideoPlaylist();
            List<Video> videos = new ArrayList<>();
            for (VideoPlaylistData.VideoPlaylist v : videoPlaylists) {
                videos.add(v.getVideo());
            }
            max_id = apiResponse.getMax_id();
            flag_loading = (max_id == null);
            if (!swiped && firstLoad && videos.size() == 0)
                textviewNoAction.setVisibility(View.VISIBLE);
            else
                textviewNoAction.setVisibility(View.GONE);

            if (swiped) {
                if (previousPosition > 0) {
                    this.peertubes.subList(0, previousPosition).clear();
                    peertubeAdapter.notifyItemRangeRemoved(0, previousPosition);
                }
                swiped = false;
            }
            if (videos.size() > 0) {
                this.peertubes.addAll(videos);
                peertubeAdapter.notifyItemRangeInserted(previousPosition, videos.size());
            }
            swipeRefreshLayout.setRefreshing(false);
            firstLoad = false;
        }
    }
}
