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.support.p000v4.app.Fragment;

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 epson.common.Constants;
import epson.print.R;
import epson.print.ImageItem;
import java.util.ArrayList;
import java.util.List;

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 this.mPhotoSelectionMode;
    }

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

    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        if (getArguments() != null) {
            this.mPhotoFolderPath = getArguments().getString(ARG_PHOTO_FOLDER_PATH);
        }
        this.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);
        this.mGridView = (GridView) inflate.findViewById(R.id.gridView);
        this.mAdapter = new Alt2ViewImageAdapter(this);
        this.mGridView.setAdapter(this.mAdapter);
        this.mGridView.setOnItemClickListener(this);
        this.mGridView.getViewTreeObserver().addOnGlobalLayoutListener(new MyGridLayoutListener(this.mGridView, this.mAdapter, getActivity().getResources().getDimensionPixelSize(R.dimen.image_selector_grid_thumbnail_spacing)));
        this.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 = this.mAdapter;
        if (alt2ViewImageAdapter != null && !this.mDoubleClickGuard) {
            int i2 = 1;
            this.mDoubleClickGuard = true;
            ImageItem imageItem = alt2ViewImageAdapter.getImageItem(i);
            if (imageItem == null || this.mImageSelector == null) {
                this.mDoubleClickGuard = false;
                return;
            }
            ImageSelectActivity imageSelectActivity = (ImageSelectActivity) getActivity();
            if (this.mPhotoSelectionMode != 1 || imageSelectActivity.singleImageMode()) {
                startViewPagerActivity(i);
            } else if (imageItem.getSelected() != 0 || this.mImageSelector.canAdd()) {
                this.mImageSelector.toggleSelect(imageItem.getPath());
                if (imageItem.getSelected() != 0) {
                    i2 = 0;
                }
                imageItem.setSelected(i2);
                this.mAdapter.notifyDataSetChanged();
                getActivity().invalidateOptionsMenu();
            } else {
                try {
                    LocalAlertDialogFragment.newInstance(getString(R.string.max_image), 3).show(getChildFragmentManager(), "alert dialog");
                } catch (IllegalStateException unused) {
                }
                this.mDoubleClickGuard = false;
                return;
            }
            this.mDoubleClickGuard = false;
        }
    }

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

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

    private void startViewPagerActivity(int i) {
        Alt2ViewImageAdapter alt2ViewImageAdapter = this.mAdapter;
        if (alt2ViewImageAdapter != null && this.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, this.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) {
            this.mImageSelector.replaceFiles(arrayList);
            Alt2ViewImageAdapter alt2ViewImageAdapter = this.mAdapter;
            if (alt2ViewImageAdapter != null) {
                int count = alt2ViewImageAdapter.getCount();
                for (int i = 0; i < count; i++) {
                    ImageItem imageItem = this.mAdapter.getImageItem(i);
                    imageItem.setSelected(this.mImageSelector.isSelected(imageItem.getPath()) ? 1 : 0);
                }
                this.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();
        this.mDoubleClickGuard = false;
        ImageThumbnailTask imageThumbnailTask = this.mImageThumbnailTask;
        if (imageThumbnailTask != null) {
            imageThumbnailTask.setSuspend(false);
        }
    }

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

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

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

    public String getFolderName() {
        return this.mPhotoFolderPath;
    }

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

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

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

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

    public void clearItem() {
        Alt2ViewImageAdapter alt2ViewImageAdapter = this.mAdapter;
        if (alt2ViewImageAdapter != null) {
            alt2ViewImageAdapter.clearImageItem();
            this.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) {
            this.mGridView = gridView;
            this.mAdapter = alt2ViewImageAdapter;
            this.mHorizontalSpacing = i;
        }

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

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