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.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.InputFilter;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import app.fedilab.fedilabtube.client.APIResponse;
import app.fedilab.fedilabtube.client.RetrofitPeertubeAPI;
import app.fedilab.fedilabtube.client.data.ChannelData;
import app.fedilab.fedilabtube.client.data.PlaylistData.Playlist;
import app.fedilab.fedilabtube.client.entities.Item;
import app.fedilab.fedilabtube.client.entities.PlaylistParams;
import app.fedilab.fedilabtube.drawer.PlaylistAdapter;
import app.fedilab.fedilabtube.viewmodel.ChannelsVM;
import app.fedilab.fedilabtube.viewmodel.PlaylistsVM;
import es.dmoral.toasty.Toasty;

import static app.fedilab.fedilabtube.MainActivity.peertubeInformation;


public class AllPlaylistsActivity extends AppCompatActivity {


    PlaylistAdapter playlistAdapter;
    private RelativeLayout mainLoader;
    private RelativeLayout textviewNoAction;
    private HashMap<Integer, String> privacyToSend;
    private Spinner set_upload_channel;
    private Spinner set_upload_privacy;
    private String idChannel;
    private List<Playlist> playlists;
    private Playlist playlistToEdit;
    private List<ChannelData.Channel> myChannels;
    private ChannelData.Channel selectedChannel;

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

        setContentView(R.layout.activity_all_playlist);

        if (getSupportActionBar() != null)
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        setTitle(R.string.playlists);


        textviewNoAction = findViewById(R.id.no_action);
        mainLoader = findViewById(R.id.loader);
        RelativeLayout nextElementLoader = findViewById(R.id.loading_next_items);
        mainLoader.setVisibility(View.VISIBLE);
        nextElementLoader.setVisibility(View.GONE);
        idChannel = null;

        PlaylistsVM viewModel = new ViewModelProvider(AllPlaylistsActivity.this).get(PlaylistsVM.class);
        viewModel.manage(PlaylistsVM.action.GET_PLAYLISTS, null, null).observe(AllPlaylistsActivity.this, apiResponse -> manageVIewPlaylists(PlaylistsVM.action.GET_PLAYLISTS, apiResponse));

        FloatingActionButton add_new = findViewById(R.id.add_new);


        LinkedHashMap<Integer, String> privaciesInit = new LinkedHashMap<>(peertubeInformation.getPrivacies());
        if (privaciesInit.size() > 0) {
            Map.Entry<Integer, String> entryInt = privaciesInit.entrySet().iterator().next();
            privacyToSend = new HashMap<>();
            privacyToSend.put(entryInt.getKey(), entryInt.getValue());
        }


        playlists = new ArrayList<>();
        ListView lv_playlist = findViewById(R.id.lv_playlist);
        playlistAdapter = new PlaylistAdapter(AllPlaylistsActivity.this, playlists, textviewNoAction);
        lv_playlist.setAdapter(playlistAdapter);

        add_new.setOnClickListener(view -> manageAlert(null));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @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);
        if (apiResponse.getError() != null) {
            Toasty.error(AllPlaylistsActivity.this, apiResponse.getError().getError(), Toast.LENGTH_LONG).show();
            return;
        }
        if (actionType == PlaylistsVM.action.GET_PLAYLISTS) {
            if (apiResponse.getPlaylists() != null && apiResponse.getPlaylists().size() > 0) {
                playlists.addAll(apiResponse.getPlaylists());
                playlistAdapter.notifyDataSetChanged();
                textviewNoAction.setVisibility(View.GONE);
            } else {
                textviewNoAction.setVisibility(View.VISIBLE);
            }
        }
    }

    public void manageAlert(Playlist playlistParam) {

        playlistToEdit = playlistParam;
        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(AllPlaylistsActivity.this);
        LayoutInflater inflater1 = getLayoutInflater();
        View dialogView = inflater1.inflate(R.layout.add_playlist, new LinearLayout(AllPlaylistsActivity.this), false);
        dialogBuilder.setView(dialogView);
        EditText display_name = dialogView.findViewById(R.id.display_name);
        EditText description = dialogView.findViewById(R.id.description);
        set_upload_channel = dialogView.findViewById(R.id.set_upload_channel);
        set_upload_privacy = dialogView.findViewById(R.id.set_upload_privacy);

        ChannelsVM viewModelC = new ViewModelProvider(AllPlaylistsActivity.this).get(ChannelsVM.class);
        viewModelC.get(RetrofitPeertubeAPI.DataType.MY_CHANNELS, null).observe(AllPlaylistsActivity.this, this::manageVIewChannels);

        display_name.setFilters(new InputFilter[]{new InputFilter.LengthFilter(120)});
        description.setFilters(new InputFilter[]{new InputFilter.LengthFilter(1000)});

        if (playlistToEdit != null) {
            display_name.setText(playlistToEdit.getDisplayName());
            description.setText(playlistToEdit.getDescription());
        }
        dialogBuilder.setPositiveButton(R.string.validate, null);
        dialogBuilder.setNegativeButton(R.string.cancel, (dialog, id) -> dialog.dismiss());

        AlertDialog alertDialog = dialogBuilder.create();
        alertDialog.setOnShowListener(dialogInterface -> {

            Button button = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
            button.setOnClickListener(view -> {
                if (display_name.getText() != null && display_name.getText().toString().trim().length() > 0) {
                    PlaylistParams playlistElement = new PlaylistParams();
                    playlistElement.setDisplayName(display_name.getText().toString().trim());
                    if (description.getText() != null && description.getText().toString().trim().length() > 0) {
                        playlistElement.setDescription(description.getText().toString().trim());
                    }
                    playlistElement.setVideoChannelId(idChannel);
                    String label;
                    Map.Entry<Integer, String> privacyM = privacyToSend.entrySet().iterator().next();
                    Item privacyItem = new Item();
                    privacyItem.setId(privacyM.getKey());
                    privacyItem.setLabel(privacyM.getValue());
                    label = privacyM.getValue();
                    if ((label.trim().compareTo("Public") == 0 && (playlistElement.getVideoChannelId() == null || playlistElement.getVideoChannelId().trim().compareTo("null") == 0))) {
                        Toasty.error(AllPlaylistsActivity.this, getString(R.string.error_channel_mandatory), Toast.LENGTH_LONG).show();
                    } else {
                        if (privacyToSend != null) {
                            playlistElement.setPrivacy((int) privacyItem.getId());
                        }
                        new Thread(() -> {
                            String playlistId;
                            if (playlistToEdit == null) {
                                APIResponse apiResponse = new RetrofitPeertubeAPI(AllPlaylistsActivity.this).createOrUpdatePlaylist(PlaylistsVM.action.CREATE_PLAYLIST, null, playlistElement, null);
                                playlistId = apiResponse.getActionReturn();
                            } else {
                                playlistId = playlistToEdit.getId();
                                new RetrofitPeertubeAPI(AllPlaylistsActivity.this).createOrUpdatePlaylist(PlaylistsVM.action.UPDATE_PLAYLIST, playlistId, playlistElement, null);
                            }
                            Handler mainHandler = new Handler(Looper.getMainLooper());
                            Runnable myRunnable = () -> {
                                Playlist playlist;
                                if (playlistToEdit == null) {
                                    playlist = new Playlist();
                                } else {
                                    playlist = playlistToEdit;
                                }
                                playlist.setId(playlistId);
                                playlist.setUuid(playlistId);
                                playlist.setDescription(playlistElement.getDescription());
                                playlist.setDisplayName(playlistElement.getDisplayName());
                                playlist.setVideoChannel(selectedChannel);
                                playlist.setPrivacy(privacyItem);
                                if (playlistToEdit == null) {
                                    playlists.add(playlist);
                                }
                                playlistAdapter.notifyDataSetChanged();
                            };
                            mainHandler.post(myRunnable);
                        }).start();
                        alertDialog.dismiss();
                    }
                } else {
                    Toasty.error(AllPlaylistsActivity.this, getString(R.string.error_display_name), Toast.LENGTH_LONG).show();
                }
            });
        });

        if (playlistToEdit == null) {
            alertDialog.setTitle(getString(R.string.action_playlist_create));
        } else {
            alertDialog.setTitle(getString(R.string.action_playlist_edit));
        }
        alertDialog.setOnDismissListener(dialogInterface -> {
            //Hide keyboard
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            assert imm != null;
            imm.hideSoftInputFromWindow(display_name.getWindowToken(), 0);
        });
        if (alertDialog.getWindow() != null)
            alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        alertDialog.show();
    }


    public void manageVIewChannels(APIResponse apiResponse) {
        if (apiResponse.getError() != null || apiResponse.getChannels() == null || apiResponse.getChannels().size() == 0) {
            if (apiResponse.getError() != null && apiResponse.getError().getError() != null)
                Toasty.error(AllPlaylistsActivity.this, apiResponse.getError().getError(), Toast.LENGTH_LONG).show();
            else
                Toasty.error(AllPlaylistsActivity.this, getString(R.string.toast_error), Toast.LENGTH_LONG).show();
            return;
        }

        //Populate channels
        myChannels = apiResponse.getChannels();
        String[] channelName = new String[myChannels.size() + 1];
        String[] channelId = new String[myChannels.size() + 1];
        int i = 1;
        channelName[0] = "";
        channelId[0] = "null";

        for (ChannelData.Channel channel : myChannels) {
            channelName[i] = channel.getName();
            channelId[i] = channel.getId();
            i++;
        }

        ArrayAdapter<String> adapterChannel = new ArrayAdapter<>(AllPlaylistsActivity.this,
                android.R.layout.simple_spinner_dropdown_item, channelName);
        set_upload_channel.setAdapter(adapterChannel);


        LinkedHashMap<String, String> translations = null;
        if (peertubeInformation.getTranslations() != null)
            translations = new LinkedHashMap<>(peertubeInformation.getTranslations());

        LinkedHashMap<Integer, String> privaciesInit = new LinkedHashMap<>(peertubeInformation.getPlaylistPrivacies());
        Map.Entry<Integer, String> entryInt = privaciesInit.entrySet().iterator().next();
        privacyToSend = new HashMap<>();
        privacyToSend.put(entryInt.getKey(), entryInt.getValue());
        LinkedHashMap<Integer, String> privacies = new LinkedHashMap<>(peertubeInformation.getPlaylistPrivacies());
        //Populate privacies
        String[] privaciesA = new String[privacies.size()];
        Iterator<Map.Entry<Integer, String>> it = privacies.entrySet().iterator();
        i = 0;
        while (it.hasNext()) {
            Map.Entry<Integer, String> pair = it.next();
            if (translations == null || translations.size() == 0 || !translations.containsKey(pair.getValue()))
                privaciesA[i] = pair.getValue();
            else
                privaciesA[i] = translations.get(pair.getValue());
            it.remove();
            i++;
        }

        ArrayAdapter<String> adapterPrivacies = new ArrayAdapter<>(AllPlaylistsActivity.this,
                android.R.layout.simple_spinner_dropdown_item, privaciesA);
        set_upload_privacy.setAdapter(adapterPrivacies);

        if (playlistToEdit != null) {
            Item privacy = playlistToEdit.getPrivacy();
            if (privacy.getId() > 0) {
                set_upload_privacy.setSelection((int) privacy.getId() - 1);
            }
        } else {
            set_upload_privacy.setSelection(2);
        }

        //Manage privacies
        set_upload_privacy.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                LinkedHashMap<Integer, String> privaciesCheck = new LinkedHashMap<>(peertubeInformation.getPrivacies());
                Iterator<Map.Entry<Integer, String>> it = privaciesCheck.entrySet().iterator();
                int i = 0;
                while (it.hasNext()) {
                    Map.Entry<Integer, String> pair = it.next();
                    if (i == position) {
                        privacyToSend = new HashMap<>();
                        privacyToSend.put(pair.getKey(), pair.getValue());
                        break;
                    }
                    it.remove();
                    i++;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        if (playlistToEdit != null) {
            Item privacy = playlistToEdit.getPrivacy();

            if (privacy.getId() > 0) {
                set_upload_privacy.setSelection((int) privacy.getId() - 1);
            }
        }

        //Manage languages
        set_upload_channel.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                idChannel = channelId[position];
                if (position > 0) {
                    selectedChannel = myChannels.get(position - 1);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        if (playlistToEdit != null) {
            int position = 0;
            int k = 1;
            for (ChannelData.Channel ac : myChannels) {
                if (playlistToEdit.getVideoChannel() != null && playlistToEdit.getVideoChannel().getId() != null && ac.getId().compareTo(playlistToEdit.getVideoChannel().getId()) == 0) {
                    position = k;
                    break;
                }
                k++;
            }
            set_upload_channel.setSelection(position);
        }
    }
}
