<commit_before>package com.mick88.dittimetable.timetable_activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
import android.support.v7.app.ActionBar.TabListener;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import com.flurry.android.FlurryAgent;
import com.mick88.dittimetable.DatabaseHelper;
import com.mick88.dittimetable.PdfDownloaderService;
import com.mick88.dittimetable.R;
import com.mick88.dittimetable.TimetableApp;
import com.mick88.dittimetable.downloader.Exceptions;
import com.mick88.dittimetable.downloader.TimetableDownloader;
import com.mick88.dittimetable.downloader.TimetableDownloader.TimetableDownloadListener;
import com.mick88.dittimetable.settings.AppSettings;
import com.mick88.dittimetable.settings.SettingsActivity;
import com.mick88.dittimetable.timetable.Timetable;
import com.mick88.dittimetable.timetable_activity.GroupSelectionDialog.GroupSelectionListener;
import com.mick88.dittimetable.utils.FontApplicator;

public class TimetableActivity extends ActionBarActivity 
									implements GroupSelectionListener, TabListener, TimetableDownloadListener
{
	private static class RetainedConfiguration
	{
		final TimetableDownloader downloader;
		final Timetable timetable;

		private RetainedConfiguration(TimetableDownloader downloader, Timetable timetable)
		{
			super();
			this.timetable = timetable;
			this.downloader = downloader;
			if (downloader != null)
				downloader.setTimetableDownloadListener(null);
		}
		
		public TimetableDownloader getDownloader()
		{
			return downloader;
		}
		
		public Timetable getTimetable()
		{
			return timetable;
		}
	}	
	
	public static final String EXTRA_ERROR_MESSAGE = "pdf_error_message";
	final int SETTINGS_REQUEST_CODE = 1;
	public static final String EXTRA_TIMETABLE = "timetable";
	
	final String logTag = "Timetable";
	String html;
	TextView textView;
	Timetable timetable = null;
	ProgressDialog progressDialog=null;
	int currentWeek = Timetable.getCurrentWeek();
	
	TimetablePageAdapter timetablePageAdapter=null;
	ViewPager viewPager=null;
	
	/**
	 * true if user is just browsing - from intent
	 */
	boolean isTemporaryTimetable = false;
	
	TimetableApp application;
	
	final private Handler uiHandler = new Handler();
	
	void toast(CharSequence message)
	{
		Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
	}
	
	private Timer timedUpdateTimer = null;
	private TimetableDownloader timetableDownloader;
       
    void downloadTimetable()
    {
    	showDownloadProgress();
    	timetableDownloader = new TimetableDownloader(getApplicationContext(), timetable, application.getSettings()).setTimetableDownloadListener(this);
    	timetableDownloader.execute();
    }
    
    void showDownloadProgress()
    {
    	showProgressPopup("Downloading timetable...");
    }
    
	@Override
	public void onTimetableDownloaded(Timetable timetable,
			RuntimeException exception)
	{
		dismissProgresPopup();
		timetableDownloader = null;
		if (exception == null)
		{
			refresh();
			new DatabaseHelper(getApplicationContext()).saveTimetable(timetable);
		}
		else if (exception instanceof Exceptions.SettingsEmptyException)
		{
			showSettingsScreen(false);
		}
		else
		{
			new AlertDialog.Builder(TimetableActivity.this)
				.setMessage(exception.getMessage())
				.setPositiveButton(R.string.retry, new OnClickListener()
				{
					
					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						downloadTimetable();						
					}
				})
				.setNegativeButton(android.R.string.cancel, null)
				.show();
		}
	}
	
	@Override
	public void onDownloadProgress(int progress, int max)
	{
		onProgress(progress, max);
	}
    
    public void setTitle()
    {
    	ActionBar actionBar = getSupportActionBar(); 	
    	
    	actionBar.setTitle(timetable.describe());
    	actionBar.setSubtitle(timetable.describeWeeks());
    }
    
    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
    	super.onConfigurationChanged(newConfig);
    }
    
    public ViewPager getViewPager()
	{
		return viewPager;
	}
    
    void setupViewPager()
    {
    	timetablePageAdapter = new TimetablePageAdapter(getSupportFragmentManager(), timetable);
    	viewPager  = (ViewPager) findViewById(R.id.pager);
    	viewPager.setAdapter(timetablePageAdapter);
    	showToday(false);
    }
    
    void showToday(boolean smooth)
    {
    	viewPager.setCurrentItem(Timetable.getTodayId(true), smooth);
    }
    
    public Map<String, String> parseQuery(String query)
    {
    	HashMap<String, String> result = new HashMap<String, String>();
    	
    	String [] vars = query.split("&");
    	for (String var : vars)
    	{
    		String [] keyValue = var.split("=", -1);
    		if (keyValue.length == 2)
    		{
    			result.put(keyValue[0], keyValue[1]);
    		}
    	}
    	
    	return result;
    }
    
	void processIntent()
	{
		Intent intent = getIntent();

		Uri address = intent.getData();
		
		Bundle extras = intent.getExtras();
		if (extras != null && extras.containsKey(EXTRA_ERROR_MESSAGE))
		{
			new AlertDialog.Builder(this)
				.setTitle("Error")
				.setMessage(extras.getString(EXTRA_ERROR_MESSAGE))
				.setPositiveButton(android.R.string.ok, null)
				.show();
		}

		if (address != null && address.getHost().equalsIgnoreCase("www.dit.ie"))
		{
			String data = address.getEncodedQuery();

			try
			{
				Map<String, String> values = parseQuery(data);
				// https://www.dit.ie/timetables/PortalServ?reqtype=timetable&ttType=COURSE&sKey=201213|DT211&sYear=2&weekRange=4603
				// 201213%7CDT211
				if (values.get("reqtype").equalsIgnoreCase("timetable") == false)
				{
					return;
				}

				String course = values.get("sKey").split("%7C")[1], 
						weeks = (Timetable
						.getCurrentSemester() == 1) ? Timetable.SEMESTER_1
						: Timetable.SEMESTER_2;
				int weekRange = Timetable.INVALID_WEEK_RANGE;
				try
				{
					Integer.parseInt(values.get("weekRange"));
				}
				catch (Exception e)
				{
					
				}
				
				int year = Integer.parseInt(values.get("sYear"));

				if (TextUtils.isEmpty(course) || year < 1 || year > 4)
				{
					return;
				}
				if (weekRange == Timetable.INVALID_WEEK_RANGE) setTimetable(new Timetable(course, year, weeks));
				else setTimetable(new Timetable(course, year, weekRange));
				
//				loadTimetable();
				isTemporaryTimetable = true;
				getSupportActionBar().setDisplayHomeAsUpEnabled(true);
			} catch (Exception e)
			{
				e.printStackTrace();
				return;
			}

			
		}
	}
    
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_timetable);

		FontApplicator fontApplicator = new FontApplicator(getAssets(), TimetableApp.FONT_NAME);
		fontApplicator.applyFont(getWindow().getDecorView());
		application = (TimetableApp) getApplication();
		
		Object retainedInstance = getLastCustomNonConfigurationInstance();
		if (retainedInstance instanceof RetainedConfiguration)
		{
			RetainedConfiguration configuration = (RetainedConfiguration) retainedInstance;
			this.timetable = configuration.getTimetable();
			TimetableDownloader downloader = configuration.getDownloader();
			if (downloader != null)
			{
				showDownloadProgress();
				downloader.setTimetableDownloadListener(this);
			}
			
		}
		if (savedInstanceState != null)
		{
			if (timetable == null)
			{<commit_msg>Assign local timetable instance instead of creating local variable<commit_after>package com.mick88.dittimetable.timetable_activity;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
import android.support.v7.app.ActionBar.TabListener;
import android.support.v7.app.ActionBarActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

import com.flurry.android.FlurryAgent;
import com.mick88.dittimetable.DatabaseHelper;
import com.mick88.dittimetable.PdfDownloaderService;
import com.mick88.dittimetable.R;
import com.mick88.dittimetable.TimetableApp;
import com.mick88.dittimetable.downloader.Exceptions;
import com.mick88.dittimetable.downloader.TimetableDownloader;
import com.mick88.dittimetable.downloader.TimetableDownloader.TimetableDownloadListener;
import com.mick88.dittimetable.settings.AppSettings;
import com.mick88.dittimetable.settings.SettingsActivity;
import com.mick88.dittimetable.timetable.Timetable;
import com.mick88.dittimetable.timetable_activity.GroupSelectionDialog.GroupSelectionListener;
import com.mick88.dittimetable.utils.FontApplicator;

public class TimetableActivity extends ActionBarActivity 
									implements GroupSelectionListener, TabListener, TimetableDownloadListener
{
	private static class RetainedConfiguration
	{
		final TimetableDownloader downloader;
		final Timetable timetable;

		private RetainedConfiguration(TimetableDownloader downloader, Timetable timetable)
		{
			super();
			this.timetable = timetable;
			this.downloader = downloader;
			if (downloader != null)
				downloader.setTimetableDownloadListener(null);
		}
		
		public TimetableDownloader getDownloader()
		{
			return downloader;
		}
		
		public Timetable getTimetable()
		{
			return timetable;
		}
	}	
	
	public static final String EXTRA_ERROR_MESSAGE = "pdf_error_message";
	final int SETTINGS_REQUEST_CODE = 1;
	public static final String EXTRA_TIMETABLE = "timetable";
	
	final String logTag = "Timetable";
	String html;
	TextView textView;
	Timetable timetable = null;
	ProgressDialog progressDialog=null;
	int currentWeek = Timetable.getCurrentWeek();
	
	TimetablePageAdapter timetablePageAdapter=null;
	ViewPager viewPager=null;
	
	/**
	 * true if user is just browsing - from intent
	 */
	boolean isTemporaryTimetable = false;
	
	TimetableApp application;
	
	final private Handler uiHandler = new Handler();
	
	void toast(CharSequence message)
	{
		Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
	}
	
	private Timer timedUpdateTimer = null;
	private TimetableDownloader timetableDownloader;
       
    void downloadTimetable()
    {
    	showDownloadProgress();
    	timetableDownloader = new TimetableDownloader(getApplicationContext(), timetable, application.getSettings()).setTimetableDownloadListener(this);
    	timetableDownloader.execute();
    }
    
    void showDownloadProgress()
    {
    	showProgressPopup("Downloading timetable...");
    }
    
	@Override
	public void onTimetableDownloaded(Timetable timetable,
			RuntimeException exception)
	{
		dismissProgresPopup();
		timetableDownloader = null;
		if (exception == null)
		{
			refresh();
			new DatabaseHelper(getApplicationContext()).saveTimetable(timetable);
		}
		else if (exception instanceof Exceptions.SettingsEmptyException)
		{
			showSettingsScreen(false);
		}
		else
		{
			new AlertDialog.Builder(TimetableActivity.this)
				.setMessage(exception.getMessage())
				.setPositiveButton(R.string.retry, new OnClickListener()
				{
					
					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						downloadTimetable();						
					}
				})
				.setNegativeButton(android.R.string.cancel, null)
				.show();
		}
	}
	
	@Override
	public void onDownloadProgress(int progress, int max)
	{
		onProgress(progress, max);
	}
    
    public void setTitle()
    {
    	ActionBar actionBar = getSupportActionBar(); 	
    	
    	actionBar.setTitle(timetable.describe());
    	actionBar.setSubtitle(timetable.describeWeeks());
    }
    
    @Override
    public void onConfigurationChanged(Configuration newConfig)
    {
    	super.onConfigurationChanged(newConfig);
    }
    
    public ViewPager getViewPager()
	{
		return viewPager;
	}
    
    void setupViewPager()
    {
    	timetablePageAdapter = new TimetablePageAdapter(getSupportFragmentManager(), timetable);
    	viewPager  = (ViewPager) findViewById(R.id.pager);
    	viewPager.setAdapter(timetablePageAdapter);
    	showToday(false);
    }
    
    void showToday(boolean smooth)
    {
    	viewPager.setCurrentItem(Timetable.getTodayId(true), smooth);
    }
    
    public Map<String, String> parseQuery(String query)
    {
    	HashMap<String, String> result = new HashMap<String, String>();
    	
    	String [] vars = query.split("&");
    	for (String var : vars)
    	{
    		String [] keyValue = var.split("=", -1);
    		if (keyValue.length == 2)
    		{
    			result.put(keyValue[0], keyValue[1]);
    		}
    	}
    	
    	return result;
    }
    
	void processIntent()
	{
		Intent intent = getIntent();

		Uri address = intent.getData();
		
		Bundle extras = intent.getExtras();
		if (extras != null && extras.containsKey(EXTRA_ERROR_MESSAGE))
		{
			new AlertDialog.Builder(this)
				.setTitle("Error")
				.setMessage(extras.getString(EXTRA_ERROR_MESSAGE))
				.setPositiveButton(android.R.string.ok, null)
				.show();
		}

		if (address != null && address.getHost().equalsIgnoreCase("www.dit.ie"))
		{
			String data = address.getEncodedQuery();

			try
			{
				Map<String, String> values = parseQuery(data);
				// https://www.dit.ie/timetables/PortalServ?reqtype=timetable&ttType=COURSE&sKey=201213|DT211&sYear=2&weekRange=4603
				// 201213%7CDT211
				if (values.get("reqtype").equalsIgnoreCase("timetable") == false)
				{
					return;
				}

				String course = values.get("sKey").split("%7C")[1], 
						weeks = (Timetable
						.getCurrentSemester() == 1) ? Timetable.SEMESTER_1
						: Timetable.SEMESTER_2;
				int weekRange = Timetable.INVALID_WEEK_RANGE;
				try
				{
					Integer.parseInt(values.get("weekRange"));
				}
				catch (Exception e)
				{
					
				}
				
				int year = Integer.parseInt(values.get("sYear"));

				if (TextUtils.isEmpty(course) || year < 1 || year > 4)
				{
					return;
				}
				if (weekRange == Timetable.INVALID_WEEK_RANGE) setTimetable(new Timetable(course, year, weeks));
				else setTimetable(new Timetable(course, year, weekRange));
				
//				loadTimetable();
				isTemporaryTimetable = true;
				getSupportActionBar().setDisplayHomeAsUpEnabled(true);
			} catch (Exception e)
			{
				e.printStackTrace();
				return;
			}

			
		}
	}
    
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.activity_timetable);

		FontApplicator fontApplicator = new FontApplicator(getAssets(), TimetableApp.FONT_NAME);
		fontApplicator.applyFont(getWindow().getDecorView());
		application = (TimetableApp) getApplication();
		
		Object retainedInstance = getLastCustomNonConfigurationInstance();
		if (retainedInstance instanceof RetainedConfiguration)
		{
			RetainedConfiguration configuration = (RetainedConfiguration) retainedInstance;
			this.timetable = configuration.getTimetable();
			this.timetableDownloader = configuration.getDownloader();
			if (timetableDownloader != null)
			{
				showDownloadProgress();
				timetableDownloader.setTimetableDownloadListener(this);
			}
			
		}
		if (savedInstanceState != null)
		{
			if (timetable == null)
			{
{'fraction_non_alphanumeric': 0.10335312818667146, 'fraction_numerical': 0.008157878951472616, 'mean_word_length': 4.081377628771716, 'pattern_counts': {'":': 0, '<': 13, '<?xml version=': 0, '>': 13, 'https://': 2, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 81, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5452685', 'n_tokens_mistral': 6007, 'n_tokens_neox': 5069, 'n_words': 927}