package app.fedilab.fedilabtube.fragment;
/* 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.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

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

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

import app.fedilab.fedilabtube.R;
import app.fedilab.fedilabtube.client.APIResponse;
import app.fedilab.fedilabtube.client.RetrofitPeertubeAPI;
import app.fedilab.fedilabtube.client.data.ChannelData;
import app.fedilab.fedilabtube.client.entities.ChannelParams;
import app.fedilab.fedilabtube.drawer.ChannelListAdapter;
import app.fedilab.fedilabtube.helper.Helper;
import app.fedilab.fedilabtube.viewmodel.ChannelsVM;
import es.dmoral.toasty.Toasty;


public class DisplayChannelsFragment extends Fragment implements ChannelListAdapter.AllChannelRemoved, ChannelListAdapter.EditAlertDialog {

    private Context context;
    private ChannelListAdapter channelListAdapter;
    private List<ChannelData.Channel> channels;
    private RelativeLayout mainLoader, nextElementLoader, textviewNoAction;
    private SwipeRefreshLayout swipeRefreshLayout;
    private String name;
    private boolean swiped;
    private RecyclerView lv_channels;
    private View rootView;
    private FloatingActionButton action_button;

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        rootView = inflater.inflate(R.layout.fragment_recyclerview, container, false);

        context = getContext();
        Bundle bundle = this.getArguments();
        channels = new ArrayList<>();
        if (bundle != null) {
            name = bundle.getString("name", null);
        }

        swiped = false;

        swipeRefreshLayout = rootView.findViewById(R.id.swipeContainer);

        if (getActivity() != null) {
            action_button = getActivity().findViewById(R.id.action_button);
            action_button.setVisibility(View.VISIBLE);
            action_button.setOnClickListener(view -> manageAlert(null));
        }

        lv_channels = rootView.findViewById(R.id.lv_elements);
        lv_channels.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
        mainLoader = rootView.findViewById(R.id.loader);
        nextElementLoader = rootView.findViewById(R.id.loading_next);
        textviewNoAction = rootView.findViewById(R.id.no_action);
        mainLoader.setVisibility(View.VISIBLE);
        nextElementLoader.setVisibility(View.GONE);
        channelListAdapter = new ChannelListAdapter(this.channels);
        channelListAdapter.allChannelRemoved = this;
        channelListAdapter.editAlertDialog = this;
        lv_channels.setAdapter(channelListAdapter);

        final LinearLayoutManager mLayoutManager;
        mLayoutManager = new LinearLayoutManager(context);
        lv_channels.setLayoutManager(mLayoutManager);

        swipeRefreshLayout.setOnRefreshListener(this::pullToRefresh);
        ChannelsVM viewModel = new ViewModelProvider(this).get(ChannelsVM.class);
        if (name != null) {
            viewModel.get(RetrofitPeertubeAPI.DataType.CHANNELS_FOR_ACCOUNT, name).observe(DisplayChannelsFragment.this.requireActivity(), this::manageViewChannels);
        } else {
            viewModel.get(RetrofitPeertubeAPI.DataType.MY_CHANNELS, null).observe(DisplayChannelsFragment.this.requireActivity(), this::manageViewChannels);
        }
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getActivity() != null && getActivity() != null) {
            View action_button = getActivity().findViewById(R.id.action_button);
            if (action_button != null) {
                action_button.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        rootView = null;
    }

    @Override
    public void onCreate(Bundle saveInstance) {
        super.onCreate(saveInstance);
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.context = context;
    }

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

    public void scrollToTop() {
        if (lv_channels != null)
            lv_channels.setAdapter(channelListAdapter);
    }

    private void manageViewChannels(APIResponse apiResponse) {
        mainLoader.setVisibility(View.GONE);
        nextElementLoader.setVisibility(View.GONE);
        if (apiResponse.getError() != null) {
            Toasty.error(context, apiResponse.getError().getError(), Toast.LENGTH_LONG).show();
            swipeRefreshLayout.setRefreshing(false);
            swiped = false;
            return;
        }
        List<ChannelData.Channel> channels = apiResponse.getChannels();
        if (!swiped && (channels == null || channels.size() == 0))
            textviewNoAction.setVisibility(View.VISIBLE);
        else
            textviewNoAction.setVisibility(View.GONE);

        if (swiped) {
            channelListAdapter = new ChannelListAdapter(this.channels);
            lv_channels.setAdapter(channelListAdapter);
            swiped = false;
        }
        if (channels != null && channels.size() > 0) {
            int currentPosition = this.channels.size();
            this.channels.addAll(channels);
            channelListAdapter.notifyItemRangeChanged(currentPosition, channels.size());
        }
        swipeRefreshLayout.setRefreshing(false);
    }

    public void pullToRefresh() {
        channels = new ArrayList<>();

        swiped = true;
        swipeRefreshLayout.setRefreshing(true);
        ChannelsVM viewModel = new ViewModelProvider(this).get(ChannelsVM.class);
        if (name != null) {
            viewModel.get(RetrofitPeertubeAPI.DataType.CHANNELS_FOR_ACCOUNT, name).observe(DisplayChannelsFragment.this.requireActivity(), this::manageViewChannels);
        } else {
            viewModel.get(RetrofitPeertubeAPI.DataType.MY_CHANNELS, null).observe(DisplayChannelsFragment.this.requireActivity(), this::manageViewChannels);
        }
    }

    @Override
    public void onAllChannelRemoved() {
        textviewNoAction.setVisibility(View.VISIBLE);
    }


    public void manageAlert(ChannelParams oldChannelValues) {

        AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
        LayoutInflater inflater1 = ((Activity) context).getLayoutInflater();
        View dialogView = inflater1.inflate(R.layout.add_channel, new LinearLayout(context), false);
        dialogBuilder.setView(dialogView);
        EditText display_name = dialogView.findViewById(R.id.display_name);
        EditText name = dialogView.findViewById(R.id.name);
        EditText description = dialogView.findViewById(R.id.description);
        if (oldChannelValues != null) {
            display_name.setText(oldChannelValues.getDisplayName());
            name.setText(oldChannelValues.getName());
            description.setText(oldChannelValues.getDescription());
            name.setEnabled(false);
        }
        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 && name.getText() != null && name.getText().toString().trim().length() > 0) {

                    ChannelParams channelCreation = new ChannelParams();
                    channelCreation.setDisplayName(display_name.getText().toString().trim());
                    channelCreation.setName(name.getText().toString().trim());
                    if (description.getText() != null && description.getText().toString().trim().length() > 0) {
                        channelCreation.setDescription(description.getText().toString().trim());
                    }
                    new Thread(() -> {
                        APIResponse apiResponse;
                        if (oldChannelValues == null) {
                            apiResponse = new RetrofitPeertubeAPI(context).createOrUpdateChannel(ChannelsVM.action.CREATE_CHANNEL, null, channelCreation);
                        } else {
                            apiResponse = new RetrofitPeertubeAPI(context).createOrUpdateChannel(ChannelsVM.action.UPDATE_CHANNEL, channelCreation.getName() + "@" + Helper.getLiveInstance(context), channelCreation);
                        }
                        Handler mainHandler = new Handler(Looper.getMainLooper());
                        Runnable myRunnable = () -> {

                            if (getActivity() == null)
                                return;
                            if (oldChannelValues == null) {
                                ChannelData.Channel channel = new ChannelData.Channel();
                                channel.setId(apiResponse.getActionReturn());
                                channel.setName(channelCreation.getName());
                                channel.setDisplayName(channelCreation.getDisplayName());
                                channel.setDescription(channelCreation.getDescription());
                                channels.add(0, channel);
                                channelListAdapter.notifyItemInserted(0);
                            } else {
                                int position = 0;
                                for (ChannelData.Channel channel : channels) {
                                    if (channel.getName().compareTo(oldChannelValues.getName()) == 0) {
                                        channel.setDescription(channelCreation.getDescription());
                                        channel.setDisplayName(channelCreation.getDisplayName());
                                        break;
                                    }
                                    position++;
                                }
                                channelListAdapter.notifyItemChanged(position);
                            }
                            action_button.setEnabled(true);
                        };
                        mainHandler.post(myRunnable);
                    }).start();
                    alertDialog.dismiss();
                    action_button.setEnabled(false);
                } else {
                    Toasty.error(context, context.getString(R.string.error_display_name_channel), Toast.LENGTH_LONG).show();
                }
            });
        });
        if (oldChannelValues == null) {
            alertDialog.setTitle(getString(R.string.action_channel_create));
        } else {
            alertDialog.setTitle(getString(R.string.action_channel_edit));
        }
        alertDialog.setOnDismissListener(dialogInterface -> {
            //Hide keyboard
            InputMethodManager imm = (InputMethodManager) context.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();
    }

    @Override
    public void show(ChannelData.Channel channel) {
        ChannelParams oldChannelValues = new ChannelParams();
        oldChannelValues.setName(channel.getName());
        oldChannelValues.setDescription(channel.getDescription());
        oldChannelValues.setDisplayName(channel.getDisplayName());
        manageAlert(oldChannelValues);
    }
}
