/*
 * TripListActivity.java
 * Shows the trip list
 */

package com.cc.infosur.main;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import com.cc.infosur.greendao.DaoMaster;
import com.cc.infosur.greendao.DaoSession;
import com.cc.infosur.greendao.TravellerInfo;
import com.cc.infosur.greendao.TravellerInfoDao;
import com.cc.infosur.greendao.TripDao;
import com.cc.infosur.greendao.TripInfo;
import com.cc.infosur.greendao.TripInfoDao;
import com.cc.infosur.greendao.DaoMaster.DevOpenHelper;

import com.cc.infosur.R;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;

public class TripListActivity extends Activity {

	// Database variables
	private SQLiteDatabase db;
	private DevOpenHelper helper;
	private DaoSession daoSession;
	private DaoMaster daoMaster;
	private TravellerInfoDao travellerInfoDao;
	private TripInfoDao tripInfoDao;
    private TripDao tripDao;

	Integer travellerId;

	@Override
	public void onBackPressed() {
		Intent intent = new Intent(TripListActivity.this, LoadActivity.class);
		startActivity(intent);
	}

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

		// Reference to actionbar
		ActionBar abar = getActionBar();
		abar.hide();

		// Block orientation if mobile
		if (!MainActivity.isTablet(this))
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

		// Prepare db
		helper = new DaoMaster.DevOpenHelper(this, "tripdb", null);
		db = helper.getWritableDatabase();
		daoMaster = new DaoMaster(db);
		daoSession = daoMaster.newSession();
		travellerInfoDao = daoSession.getTravellerInfoDao();
        tripDao = daoSession.getTripDao();


        // Get bundle extras
		Bundle bundle = getIntent().getExtras();
		travellerId = bundle.getInt("travellerId");

        // If there is travellerInfo (user / traveler) & trip Data on the GreenDao DATABASE
        // We propose the traveler to display the previous trip because he was already been logged once
        // ONLY if this trip belong this user / traveler
        if(travellerInfoDao.loadAll().size() > 0 && tripDao.loadAll().size() > 0) {

            // Get the trip id which is saved in the DB
            long tripidDB = tripDao.loadAll().get(0).getId();

            // Listing all the trips of the current traveler
            TravellerInfo travellerInfo = travellerInfoDao.load(travellerId.longValue());
            List<TripInfo> trips = travellerInfo.getTrips();

            for (int i = 0; i < trips.size(); i++) {

                // Check if the trip id saved belong to the current traveler : if YES, we can propose him to display a previous trip
                if( tripidDB == trips.get(i).getId() ) {
                    showPreviousTripDialog();
                }
            }

        }



		if (travellerId == 0) { // Demo trip
			TextView tv = (TextView) findViewById(R.id.dateTextView);
			tv.setVisibility(View.GONE);
			String json = null;
			try {
				//Loads the demotrip json stored on the device
				InputStream is = getAssets().open("demotrip2.json");
				int size = is.available();
				byte[] buffer = new byte[size];
				is.read(buffer);
				is.close();
				json = new String(buffer, "UTF-8");
			} catch (IOException ex) {
				ex.printStackTrace();
				return;
			}
			//Call the parsing json task
			new DownloadFilesTask(this, json).execute();
		} else { // Loads the trip list
			
			//if(travellerInfoDao.loadAll().size() > 0) {
			if(travellerInfoDao.load(travellerId.longValue()) != null) {
						
				TravellerInfo travellerInfo = travellerInfoDao.load(travellerId.longValue());
				List<TripInfo> trips = travellerInfo.getTrips();

				Log.i("TRIPS", "trav: " + travellerId);
				for (int i = 0; i < trips.size(); i++) {
					Log.i("TRIPS", trips.get(i).getId() + "");
				}

				// Set the custom adapter for the list view
				ListView questionsListView = (ListView) findViewById(R.id.tripList);
				TripListAdapter adapter = new TripListAdapter(this,R.layout.simplereportinglayout, trips);
				questionsListView.setAdapter(adapter);
			}

		}
	}

    public void showPreviousTripDialog() {

        new AlertDialog.Builder(TripListActivity.this)
                .setTitle("Programme sauvegardé")
                .setMessage("Voulez vous télécharger le programme déjà sauvegardé ?")
                .setPositiveButton("Oui",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(TripListActivity.this, MainActivity.class);
                                startActivity(intent);
                            }
                        })
                .setNegativeButton("Non",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).show();

    }

	// Prepare data and send to the next activity, MainActivity with the selected trip
	public void showTrip(int eppParkId, int etpParkId) {
		Intent intent = new Intent(TripListActivity.this, MainActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
		Bundle bundle = new Bundle();
		bundle.putLong("travellerId", travellerId);
		bundle.putInt("eppParkId", eppParkId);
		bundle.putInt("etpParkId", etpParkId);
		intent.putExtras(bundle);
		startActivity(intent);
	}
}
