package epson.print.imgsel;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ListAdapter;

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

import epson.common.Constants;
import epson.print.ImageItem;
import epson.print.R;

public class ImageGridFragment extends Fragment implements AdapterView.OnItemClickListener {
    private static final String ARG_PHOTO_FOLDER_PATH = "photo_folder_path";
    public static final int DIALOG_CODE_NOTIFY = 3;
    public static final int PHOTO_SELECTION_MODE_DEFAULT = 0;
    public static final int PHOTO_SELECTION_MODE_MULTISELECT = 1;
    public static final int PHOTO_SELECTION_MODE_ZOOM = 0;
    private static final int REQUEST_CODE_IMAGE_PAGER = 2;
    private Alt2ViewImageAdapter mAdapter;
    private boolean mDoubleClickGuard;
    private GridView mGridView;
    private ImageFindTask mImageFindTask;
    private ImageSelector mImageSelector;
    private ImageThumbnailTask mImageThumbnailTask;
    private String mPhotoFolderPath;
    private int mPhotoSelectionMode = 0;

    public interface ImageGridListener {
        ImageFinder getImageFinder();

        ImageSelector getImageSelector();
    }

    public static ImageGridFragment newInstance(String str) {
        ImageGridFragment imageGridFragment = new ImageGridFragment();
        Bundle bundle = new Bundle();
        bundle.putString(ARG_PHOTO_FOLDER_PATH, str);
        imageGridFragment.setArguments(bundle);
        return imageGridFragment;
    }

    protected static SharedPreferences getPreferences(Context context) {
        return context.getSharedPreferences(Constants.PREFS_PHOTO, 0);
    }

    public int getPhotoSelectionMode() {
        return mPhotoSelectionMode;
    }

    public void setPhotoSelectionMode(int i) {
        mPhotoSelectionMode = i;
        SharedPreferences.Editor edit = getPreferences(getActivity()).edit();
        edit.putInt(Constants.PHOTO_SELECT_MODE, mPhotoSelectionMode);
        edit.commit();
    }

    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        if (getArguments() != null) {
            mPhotoFolderPath = getArguments().getString(ARG_PHOTO_FOLDER_PATH);
        }
        mPhotoSelectionMode = getPreferences(getActivity()).getInt(Constants.PHOTO_SELECT_MODE, 0);
    }

    public View onCreateView(LayoutInflater layoutInflater, ViewGroup viewGroup, Bundle bundle) {
        View inflate = layoutInflater.inflate(R.layout.fragment_image_grid, viewGroup, false);
        mGridView = (GridView) inflate.findViewById(R.id.gridView);
        mAdapter = new Alt2ViewImageAdapter(this);
        mGridView.setAdapter(mAdapter);
        mGridView.setOnItemClickListener(this);
        mGridView.getViewTreeObserver().addOnGlobalLayoutListener(new MyGridLayoutListener(mGridView, mAdapter, getActivity().getResources().getDimensionPixelSize(R.dimen.image_selector_grid_thumbnail_spacing)));
        mImageSelector = ((ImageGridListener) getActivity()).getImageSelector();
        getActivity().invalidateOptionsMenu();
        restartImageFindTask();
        return inflate;
    }

    public void onActivityCreated(Bundle bundle) {
        super.onActivityCreated(bundle);
    }

    public void onItemClick(AdapterView<?> adapterView, View view, int i, long j) {
        Alt2ViewImageAdapter alt2ViewImageAdapter = mAdapter;
        if (alt2ViewImageAdapter != null && !this.mDoubleClickGuard) {
            int i2 = 1;
            mDoubleClickGuard = true;
            ImageItem imageItem = alt2ViewImageAdapter.getImageItem(i);
            if (imageItem == null || mImageSelector == null) {
                mDoubleClickGuard = false;
                return;
            }
            ImageSelectActivity imageSelectActivity = (ImageSelectActivity) getActivity();
            if (mPhotoSelectionMode != 1 || imageSelectActivity.singleImageMode()) {
                startViewPagerActivity(i);
            } else if (imageItem.getSelected() != 0 || mImageSelector.canAdd()) {
                mImageSelector.toggleSelect(imageItem.getPath());
                if (imageItem.getSelected() != 0) {
                    i2 = 0;
                }
                imageItem.setSelected(i2);
                mAdapter.notifyDataSetChanged();
                getActivity().invalidateOptionsMenu();
            } else {
                try {
                    LocalAlertDialogFragment.newInstance(getString(R.string.max_image), 3).show(getChildFragmentManager(), "alert dialog");
                } catch (IllegalStateException unused) {
                }
                mDoubleClickGuard = false;
                return;
            }
            mDoubleClickGuard = false;
        }
    }

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

    public void onDetach() {
        super.onDetach();
        Log.d("ImageGridFragment", "onDetach()");
        ImageFindTask imageFindTask = mImageFindTask;
        if (imageFindTask != null) {
            imageFindTask.cancel(true);
            mImageFindTask = null;
        }
        ImageThumbnailTask imageThumbnailTask = mImageThumbnailTask;
        if (imageThumbnailTask != null) {
            imageThumbnailTask.cancel(true);
            mImageThumbnailTask = null;
        }
        Alt2ViewImageAdapter alt2ViewImageAdapter = mAdapter;
        if (alt2ViewImageAdapter != null) {
            alt2ViewImageAdapter.recycleBitmap();
            mAdapter = null;
            mGridView.setAdapter((ListAdapter) null);
        }
        FragmentActivity activity = getActivity();
        if (activity != null) {
            activity.invalidateOptionsMenu();
        }
    }

    private void startViewPagerActivity(int i) {
        Alt2ViewImageAdapter alt2ViewImageAdapter = mAdapter;
        if (alt2ViewImageAdapter != null && mImageSelector != null) {
            ArrayList<String> fileList = alt2ViewImageAdapter.getFileList();
            ImageSelectActivity imageSelectActivity = (ImageSelectActivity) getActivity();
            if (imageSelectActivity != null) {
                Intent intent = new Intent(imageSelectActivity, imageSelectActivity.showNfcInvalidMessageOnPagerActivity() ? ImageViewPagerWithNfcInvalidPrintMessageActivity.class : ImageViewPagerActivity.class);
                intent.putExtra(ImageViewPagerActivity.PARAMS_KEY_POSITION, i);
                intent.putExtra(ImageViewPagerActivity.PARAMS_KEY_SELECTOR, mImageSelector.getFileArrayList());
                intent.putExtra(ImageViewPagerActivity.PARAMS_SINGLE_FILE_MODE, imageSelectActivity.singleImageMode());
                intent.putExtra(ImageViewPagerActivity.PARAMS_MESSAGE_TYPE, imageSelectActivity.getMessageType());
                ImageViewPagerActivity.setFileList(fileList);
                startActivityForResult(intent, 2);
            }
        }
    }

    public void goNext() {
        ((ImageSelectActivity) getActivity()).goNext();
    }

    public void updateImageSelector(ArrayList<String> arrayList) {
        if (arrayList != null) {
            mImageSelector.replaceFiles(arrayList);
            Alt2ViewImageAdapter alt2ViewImageAdapter = mAdapter;
            if (alt2ViewImageAdapter != null) {
                int count = alt2ViewImageAdapter.getCount();
                for (int i = 0; i < count; i++) {
                    ImageItem imageItem = mAdapter.getImageItem(i);
                    imageItem.setSelected(mImageSelector.isSelected(imageItem.getPath()) ? 1 : 0);
                }
                mAdapter.notifyDataSetChanged();
            }
            FragmentActivity activity = getActivity();
            if (activity != null) {
                activity.invalidateOptionsMenu();
            }
        }
    }

    public void onActivityResult(int i, int i2, Intent intent) {
        if (i == 2) {
            ArrayList<String> stringArrayListExtra = intent.getStringArrayListExtra(ImageViewPagerActivity.RETURN_KEY_SELECTOR);
            if (stringArrayListExtra != null) {
                updateImageSelector(stringArrayListExtra);
            }
            if (i2 == 10) {
                goNext();
            }
        }
    }

    public void onResume() {
        super.onResume();
        mDoubleClickGuard = false;
        ImageThumbnailTask imageThumbnailTask = mImageThumbnailTask;
        if (imageThumbnailTask != null) {
            imageThumbnailTask.setSuspend(false);
        }
    }

    public void onPause() {
        super.onPause();
        ImageThumbnailTask imageThumbnailTask = mImageThumbnailTask;
        if (imageThumbnailTask != null) {
            imageThumbnailTask.setSuspend(true);
        }
    }

    private void restartImageFindTask() {
        ImageGridListener imageGridListener = (ImageGridListener) getActivity();
        if (imageGridListener != null) {
            mImageFindTask = new ImageFindTask(this, mPhotoFolderPath);
            mImageFindTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new ImageFinder[]{imageGridListener.getImageFinder()});
            mImageThumbnailTask = new ImageThumbnailTask(this);
        }
    }

    public boolean isImageSelected(String str) {
        return mImageSelector.isSelected(str);
    }

    public String getFolderName() {
        return mPhotoFolderPath;
    }

    public void addItem(List<ImageItem> list) {
        if (list != null && mAdapter != null && mImageThumbnailTask != null) {
            for (ImageItem next : list) {
                mAdapter.add(next);
                mImageThumbnailTask.addLast(next);
            }
            mAdapter.notifyDataSetChanged();
            if (mImageThumbnailTask.getStatus() == AsyncTask.Status.PENDING) {
                mImageThumbnailTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new Void[0]);
            }
        }
    }

    public void updateItem(ImageItem imageItem) {
        Alt2ViewImageAdapter alt2ViewImageAdapter;
        int position;
        if (imageItem != null && (alt2ViewImageAdapter = mAdapter) != null && mGridView != null && (position = alt2ViewImageAdapter.getPosition(imageItem)) != -1) {
            mAdapter.getImageItem(position).setBitmap(imageItem.getBitmap());
            int firstVisiblePosition = mGridView.getFirstVisiblePosition();
            int lastVisiblePosition = mGridView.getLastVisiblePosition();
            if (firstVisiblePosition <= position && lastVisiblePosition >= position) {
                mAdapter.notifyDataSetChanged();
            }
        }
    }

    public void updateData() {
        Alt2ViewImageAdapter alt2ViewImageAdapter = mAdapter;
        if (alt2ViewImageAdapter != null && mGridView != null && mImageThumbnailTask != null) {
            alt2ViewImageAdapter.notifyDataSetChanged();
            mImageThumbnailTask.setFinish(true);
        }
    }

    public void changeThumnailPriority(ImageItem imageItem) {
        ImageThumbnailTask imageThumbnailTask = mImageThumbnailTask;
        if (imageThumbnailTask != null) {
            imageThumbnailTask.moveToFirst(imageItem);
        }
    }

    public void clearItem() {
        Alt2ViewImageAdapter alt2ViewImageAdapter = mAdapter;
        if (alt2ViewImageAdapter != null) {
            alt2ViewImageAdapter.clearImageItem();
            mAdapter.notifyDataSetChanged();
        }
    }

    private static class MyGridLayoutListener implements ViewTreeObserver.OnGlobalLayoutListener {
        Alt2ViewImageAdapter mAdapter;
        private GridView mGridView;
        private int mHorizontalSpacing;

        public MyGridLayoutListener(GridView gridView, Alt2ViewImageAdapter alt2ViewImageAdapter, int i) {
            mGridView = gridView;
            mAdapter = alt2ViewImageAdapter;
            mHorizontalSpacing = i;
        }

        @TargetApi(16)
        public void onGlobalLayout() {
            int numColumns = mGridView.getNumColumns();
            if (numColumns <= 0) {
                return;
            }
            if (Build.VERSION.SDK_INT >= 16) {
                setNewVerticalParams();
                mGridView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                return;
            }
            int width = mGridView.getWidth();
            int i = mHorizontalSpacing;
            mAdapter.setHeight(((width + i) / numColumns) - i);
            mGridView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        }

        @TargetApi(16)
        private void setNewVerticalParams() {
            mGridView.setVerticalSpacing(mGridView.getHorizontalSpacing());
            mAdapter.setHeight(mGridView.getColumnWidth());
        }
    }
}
