// Copyright (c) 2017-2018, Tom Geiselmann
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software
// and associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY,WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

package com.none.tom.simplerssreader.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.SparseBooleanArray;
import android.view.KeyEvent;

import com.none.tom.simplerssreader.R;
import com.none.tom.simplerssreader.activity.MainActivity;
import com.none.tom.simplerssreader.feed.CurrentFeed;

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

public class FilterByCategoriesFragment extends DialogFragment {
    public static final String TAG = "filter_by_category_fragment";

    private static final String KEY_CATEGORIES = "key_categories";

    private static FilterByCategoriesFragment sFilterByCategoriesFragment;

    private String[] mCategories;
    private SparseBooleanArray mCheckedCategories;

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

        final Bundle args = getArguments();

        mCategories = args.getStringArray(KEY_CATEGORIES);
        mCheckedCategories = new SparseBooleanArray();
    }

    @Override
    public Dialog onCreateDialog(final Bundle savedInstanceState) {
        final Activity activity = getActivity();

        final AlertDialog.Builder filterByCategoryDialog = new AlertDialog.Builder(activity);

        filterByCategoryDialog.setTitle(R.string.action_filter_by_categories);

        filterByCategoryDialog.setMultiChoiceItems(mCategories, null,
                new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialogInterface,
                                        final int position, final boolean isChecked) {
                        mCheckedCategories.append(position, isChecked);
                    }
        });

        filterByCategoryDialog.setPositiveButton(android.R.string.ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(final DialogInterface dialogInterface, final int ignored) {
                        if (mCheckedCategories.size() > 0) {
                            final List<String> checkedCategories = new ArrayList<>();

                            for (int i = 0; i < mCategories.length; i++) {
                                if (mCheckedCategories.get(i, false)) {
                                    checkedCategories.add(mCategories[i]);
                                }
                            }

                            final List<Integer> positions =
                                    CurrentFeed.getCategoriesPositions(checkedCategories);

                            ((MainActivity) activity).startActionMode(positions);
                        }
                    }
        });

        filterByCategoryDialog.setNegativeButton(android.R.string.cancel, null);

        final AlertDialog dialog = filterByCategoryDialog.create();

        dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(final DialogInterface dialogInterface, final int keyCode,
                                 final KeyEvent keyEvent) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    dialog.dismiss();

                    return true;
                }

                return false;
            }
        });

        setCancelable(false);
        dialog.setCanceledOnTouchOutside(false);

        return dialog;
    }

    public static FilterByCategoriesFragment getInstance(final List<String> categories) {
        if (sFilterByCategoriesFragment == null) {
            final Bundle args = new Bundle();

            args.putStringArray(KEY_CATEGORIES, categories.toArray(new String[0]));

            sFilterByCategoriesFragment = new FilterByCategoriesFragment();

            sFilterByCategoriesFragment.setArguments(args);
        } else {
            final Bundle args = sFilterByCategoriesFragment.getArguments();

            args.clear();

            args.putStringArray(KEY_CATEGORIES, categories.toArray(new String[0]));
        }

        return sFilterByCategoriesFragment;
    }
}