<commit_before>/*
 * Copyright 2014 <NAME>
 * Copyright 2014 <NAME>
 * Copyright 2014 <NAME>
 * Copyright 2014 <NAME>
 * Copyright 2014 <NAME>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ca.ualberta.cmput301w14t08.geochan.fragments;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import ca.ualberta.cmput301w14t08.geochan.R;
import ca.ualberta.cmput301w14t08.geochan.adapters.ThreadViewAdapter;
import ca.ualberta.cmput301w14t08.geochan.helpers.ConnectivityBroadcastReceiver;
import ca.ualberta.cmput301w14t08.geochan.helpers.ConnectivityHelper;
import ca.ualberta.cmput301w14t08.geochan.helpers.HashHelper;
import ca.ualberta.cmput301w14t08.geochan.helpers.LocationListenerService;
import ca.ualberta.cmput301w14t08.geochan.helpers.SortUtil;
import ca.ualberta.cmput301w14t08.geochan.helpers.Toaster;
import ca.ualberta.cmput301w14t08.geochan.interfaces.UpdateDialogListenerInterface;
import ca.ualberta.cmput301w14t08.geochan.managers.CacheManager;
import ca.ualberta.cmput301w14t08.geochan.managers.PreferencesManager;
import ca.ualberta.cmput301w14t08.geochan.managers.ThreadManager;
import ca.ualberta.cmput301w14t08.geochan.models.Comment;
import ca.ualberta.cmput301w14t08.geochan.models.FavouritesLog;
import ca.ualberta.cmput301w14t08.geochan.models.GeoLocation;
import ca.ualberta.cmput301w14t08.geochan.models.ThreadComment;
import eu.erikw.PullToRefreshListView;
import eu.erikw.PullToRefreshListView.OnRefreshListener;

/**
 * Fragment which displays the contents of a ThreadComment and performs all
 * actions on the objects in that ThreadComment.
 * 
 * @author <NAME>
 * @author <NAME>
 */
public class ThreadViewFragment extends Fragment implements UpdateDialogListenerInterface {
	private BroadcastReceiver updateReceiver;
    private PullToRefreshListView threadView;
    private ThreadViewAdapter adapter;
    private int threadIndex;
    private CacheManager cache = null;
    private ThreadComment thread = null;
    private ConnectivityHelper connectHelper = null;
    private LocationListenerService locationListener = null;
    private PreferencesManager prefManager = null;
    private int container;
    private int isFavCom;
	private boolean refresh = false;
    private static int locSortFlag = 0;

    /**
     * Gets the fragment arguments, retrieves correct
     * ThreadComment object from either ThreadList or Cache or FavouritesLog,
     * Starts the refresh from server.
     * @param savedInstanceState The previously saved state of the Fragment.
     */
    @Override
    public void onCreate (Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	Bundle bundle = getArguments();
    	threadIndex = (int) bundle.getLong("id");
    	isFavCom = bundle.getInt("favCom");
    	thread = bundle.getParcelable("thread");
    	// Assign custom adapter to the thread listView.
    	adapter = new ThreadViewAdapter(getActivity(), thread, getFragmentManager(), threadIndex);
    	if (isFavCom != -1) {
    		connectHelper = ConnectivityHelper.getInstance();
    		cache = CacheManager.getInstance();
    		ArrayList<Comment> comments = cache.deserializeThreadCommentById(thread.getId());
    		if (comments != null) {
    			thread.getBodyComment().setChildren(comments);
    		}
    		if (!connectHelper.isConnected()) {
    			Toaster.toastShort("No network connection.");
    		}
        }
    }
    
    /**
     * Sets the proper sort option in our options menu.
     * 
     * @param menu The fragment's menu.
     */
	@Override
	public void onPrepareOptionsMenu(Menu menu){
		int sortType = prefManager.getCommentSort();
		setSortCheck(sortType, menu);
		super.onPrepareOptionsMenu(menu);
	}
	
	/**
	 * Checks the proper sort option in our options menu.
	 * @param sort Code for the sort type.
	 * @param menu The fragment's menu.
	 */
	private void setSortCheck(int sort, Menu menu){
		MenuItem item;
		switch(sort){
		case SortUtil.SORT_DATE_NEWEST:
			item = menu.findItem(R.id.comment_sort_date_new);
			item.setChecked(true);
			return;
		case SortUtil.SORT_DATE_OLDEST:
			item = menu.findItem(R.id.comment_sort_date_new);
			item.setChecked(true);
			return;
		case SortUtil.SORT_LOCATION:
			item = menu.findItem(R.id.comment_sort_location);
			item.setChecked(true);
			return;
		case SortUtil.SORT_USER_SCORE_HIGHEST:
			item = menu.findItem(R.id.comment_sort_score_high);
			item.setChecked(true);
			return;
		case SortUtil.SORT_USER_SCORE_LOWEST:
			item = menu.findItem(R.id.comment_sort_score_low);
			item.setChecked(true);
			return;
		case SortUtil.SORT_IMAGE:
			item = menu.findItem(R.id.comment_sort_image);
			item.setChecked(true);
			return;
		default:
			return;
		}
	}

    /**
     * Initializes the variables used in displaying the contents of a
     * thread. If the user just returned from selecting a custom location to
     * sort by, it sorts the comments accordingly and resets locSortFlag.
     */
    @Override
    public void onResume() {
        setHasOptionsMenu(true);
        if (locationListener == null) {
            locationListener = new LocationListenerService(getActivity());
        }
        if (prefManager == null) {
            prefManager = PreferencesManager.getInstance();
        }
        if (locSortFlag == 1) {
            prefManager.setCommentSort(SortUtil.SORT_LOCATION);
            SortUtil.sortComments(SortUtil.SORT_LOCATION, thread.getBodyComment().getChildren());
            adapter = new ThreadViewAdapter(getActivity(), thread, getFragmentManager(),
                    threadIndex);
            threadView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
            locSortFlag = 0;
        }
        super.onResume();
    }

    /**
     * Set up the fragment UI.
     * 
     * @param inflater The LayoutInflater used to inflate the fragment's UI.
     * @param container The parent View that the  fragment's UI is attached to.
     * @param savedInstanceState The previously saved state of the fragment.
     * @return The View for the fragment's UI.
     * 
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_thread_view, container, false);
    }

    /**<commit_msg>Fixed ThreadView crash<commit_after>/*
 * Copyright 2014 <NAME>
 * Copyright 2014 <NAME>
 * Copyright 2014 <NAME>
 * Copyright 2014 <NAME>
 * Copyright 2014 <NAME>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ca.ualberta.cmput301w14t08.geochan.fragments;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.ArrayList;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import ca.ualberta.cmput301w14t08.geochan.R;
import ca.ualberta.cmput301w14t08.geochan.adapters.ThreadViewAdapter;
import ca.ualberta.cmput301w14t08.geochan.helpers.ConnectivityBroadcastReceiver;
import ca.ualberta.cmput301w14t08.geochan.helpers.ConnectivityHelper;
import ca.ualberta.cmput301w14t08.geochan.helpers.HashHelper;
import ca.ualberta.cmput301w14t08.geochan.helpers.LocationListenerService;
import ca.ualberta.cmput301w14t08.geochan.helpers.SortUtil;
import ca.ualberta.cmput301w14t08.geochan.helpers.Toaster;
import ca.ualberta.cmput301w14t08.geochan.interfaces.UpdateDialogListenerInterface;
import ca.ualberta.cmput301w14t08.geochan.managers.CacheManager;
import ca.ualberta.cmput301w14t08.geochan.managers.PreferencesManager;
import ca.ualberta.cmput301w14t08.geochan.managers.ThreadManager;
import ca.ualberta.cmput301w14t08.geochan.models.Comment;
import ca.ualberta.cmput301w14t08.geochan.models.FavouritesLog;
import ca.ualberta.cmput301w14t08.geochan.models.GeoLocation;
import ca.ualberta.cmput301w14t08.geochan.models.ThreadComment;
import eu.erikw.PullToRefreshListView;
import eu.erikw.PullToRefreshListView.OnRefreshListener;

/**
 * Fragment which displays the contents of a ThreadComment and performs all
 * actions on the objects in that ThreadComment.
 * 
 * @author <NAME>
 * @author <NAME>
 */
public class ThreadViewFragment extends Fragment implements UpdateDialogListenerInterface {
	private BroadcastReceiver updateReceiver;
    private PullToRefreshListView threadView;
    private ThreadViewAdapter adapter;
    private int threadIndex;
    private CacheManager cache = null;
    private ThreadComment thread = null;
    private ConnectivityHelper connectHelper = null;
    private LocationListenerService locationListener = null;
    private PreferencesManager prefManager = null;
    private int container;
    private int isFavCom;
	private boolean refresh = false;
    private static int locSortFlag = 0;

    /**
     * Gets the fragment arguments, retrieves correct
     * ThreadComment object from either ThreadList or Cache or FavouritesLog,
     * Starts the refresh from server.
     * @param savedInstanceState The previously saved state of the Fragment.
     */
    @Override
    public void onCreate (Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	Bundle bundle = getArguments();
    	threadIndex = (int) bundle.getLong("id");
    	isFavCom = bundle.getInt("favCom");
    	thread = bundle.getParcelable("thread");
        if (locationListener == null) {
            locationListener = new LocationListenerService(getActivity());
        }
        if (prefManager == null) {
            prefManager = PreferencesManager.getInstance();
        }
    	// Assign custom adapter to the thread listView.
    	adapter = new ThreadViewAdapter(getActivity(), thread, getFragmentManager(), threadIndex);
    	if (isFavCom != -1) {
    		connectHelper = ConnectivityHelper.getInstance();
    		cache = CacheManager.getInstance();
    		ArrayList<Comment> comments = cache.deserializeThreadCommentById(thread.getId());
    		if (comments != null) {
    			thread.getBodyComment().setChildren(comments);
    		}
    		if (!connectHelper.isConnected()) {
    			Toaster.toastShort("No network connection.");
    		}
        }
    }
    
    /**
     * Sets the proper sort option in our options menu.
     * 
     * @param menu The fragment's menu.
     */
	@Override
	public void onPrepareOptionsMenu(Menu menu){
		int sortType = prefManager.getCommentSort();
		setSortCheck(sortType, menu);
		super.onPrepareOptionsMenu(menu);
	}
	
	/**
	 * Checks the proper sort option in our options menu.
	 * @param sort Code for the sort type.
	 * @param menu The fragment's menu.
	 */
	private void setSortCheck(int sort, Menu menu){
		MenuItem item;
		switch(sort){
		case SortUtil.SORT_DATE_NEWEST:
			item = menu.findItem(R.id.comment_sort_date_new);
			item.setChecked(true);
			return;
		case SortUtil.SORT_DATE_OLDEST:
			item = menu.findItem(R.id.comment_sort_date_new);
			item.setChecked(true);
			return;
		case SortUtil.SORT_LOCATION:
			item = menu.findItem(R.id.comment_sort_location);
			item.setChecked(true);
			return;
		case SortUtil.SORT_USER_SCORE_HIGHEST:
			item = menu.findItem(R.id.comment_sort_score_high);
			item.setChecked(true);
			return;
		case SortUtil.SORT_USER_SCORE_LOWEST:
			item = menu.findItem(R.id.comment_sort_score_low);
			item.setChecked(true);
			return;
		case SortUtil.SORT_IMAGE:
			item = menu.findItem(R.id.comment_sort_image);
			item.setChecked(true);
			return;
		default:
			return;
		}
	}

    /**
     * Initializes the variables used in displaying the contents of a
     * thread. If the user just returned from selecting a custom location to
     * sort by, it sorts the comments accordingly and resets locSortFlag.
     */
    @Override
    public void onResume() {
        setHasOptionsMenu(true);
        if (locSortFlag == 1) {
            prefManager.setCommentSort(SortUtil.SORT_LOCATION);
            SortUtil.sortComments(SortUtil.SORT_LOCATION, thread.getBodyComment().getChildren());
            adapter = new ThreadViewAdapter(getActivity(), thread, getFragmentManager(),
                    threadIndex);
            threadView.setAdapter(adapter);
            adapter.notifyDataSetChanged();
            locSortFlag = 0;
        }
        super.onResume();
    }

    /**
     * Set up the fragment UI.
     * 
     * @param inflater The LayoutInflater used to inflate the fragment's UI.
     * @param container The parent View that the  fragment's UI is attached to.
     * @param savedInstanceState The previously saved state of the fragment.
     * @return The View for the fragment's UI.
     * 
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_thread_view, container, false);
    }

    /**
{'fraction_non_alphanumeric': 0.08846383741781232, 'fraction_numerical': 0.019658630537291624, 'mean_word_length': 3.815478094019827, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5541811', 'n_tokens_mistral': 4774, 'n_tokens_neox': 4361, 'n_words': 1100}