package com.cc.infosur.main;

import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.cc.infosur.greendao.*;
import com.cc.infosur.greendao.DaoMaster.DevOpenHelper;

import com.cc.infosur.mytrip.MyTripFragment;

import java.util.HashMap;
import java.util.Stack;

import com.cc.infosur.R;
import com.facebook.stetho.Stetho;

/**
 * Class MainActivity
 */
public class MainActivity extends FragmentActivity{
	private Bundle b1;
	private Bundle b2;
	private static MainActivity sActivity = null;

	// Static variables
	private static long travellerId;
	private static int eppParkId = 3;
	private static int etpParkId;
	private static int tripId = 0;

	// Database variables
    private SQLiteDatabase db;
    private DevOpenHelper helper;
    private DaoSession daoSession;
    private DaoMaster daoMaster;
    private TripDao tripDao;
    private DayServiceRelDao dayServiceRelDao;
    private DayDao dayDao;
    private ServiceDao serviceDao;
    private TravellerInfoDao travellerInfoDao;
    private ParkInfoDao parkInfoDao;

    private LocationManager lm;

	private boolean hiddenManually = false;

	// Public method to check if the activity is running
	public static MainActivity getInstance() {
		return sActivity;
	}
	
	public static long getTravellerId(){
		return travellerId;
	}
	
	public static void setTripId(int id){
		tripId = id;
	}
	
	public static int getTripId(){
		return tripId;
	}

	public static int getEppParkId() {
		return eppParkId;
	}
	
	public static int getEtpParkId() {
		return etpParkId;
	}

	// Stacks
	public HashMap<String, Stack<Fragment>> mStacks;

    /**
     * Function onBackPressed()
     */
	@Override
	public void onBackPressed() {
		super.onBackPressed();
	}

    /**
     * Function onResume()
     */
	@Override
	protected void onResume() {
		super.onResume();
		MainActivity.activityResumed();
	}

    /**
     * Function onPause()
     */
	@Override
	protected void onPause() {
		super.onPause();
		MainActivity.activityPaused();
	}

    /**
     * Function isActivityVisible()
     * @return
     *
     * Check activity visibility
     */
	public static boolean isActivityVisible() {
		return activityVisible;
	}

    /**
     * Function activityResumed()
     */
	public static void activityResumed() {
		activityVisible = true;
	}

    /**
     * Function activityPaused()
     */
	public static void activityPaused() {
		activityVisible = false;
	}

	private static boolean activityVisible;

    /**
     * Function onConfigurationChanged()
     * @param newConfig
     */
	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// setContentView(R.layout.activity_main);
	}

    /**
     * Function onSaveInstanceState()
     * @param savedInstanceState
     */
	@Override
	public void onSaveInstanceState(Bundle savedInstanceState) {
		super.onSaveInstanceState(savedInstanceState);
	}

    /**
     * Function onRestoreInstanceState()
     * @param savedInstanceState
     */
	@Override
	public void onRestoreInstanceState(Bundle savedInstanceState) {
		super.onRestoreInstanceState(savedInstanceState);
	}

    /**
     * Function onDestroy()
     */
	@Override
	protected void onDestroy() {
		super.onDestroy();
		//stopService(new Intent(MainActivity.this, GPSLoggerService.class));
	}

    /**
     * Function logout()
     *
     * When the user logs out, reset some variables and stop services
     */
	public void logout(){
		//stopService(new Intent(MainActivity.this, GPSLoggerService.class));
    	Intent intent = new Intent(MainActivity.this, LoadActivity.class);
		startActivity(intent);
	}

    /**
     * Function onCreate()
     * @param savedInstanceState
     */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Stetho.initializeWithDefaults(this);
		setContentView(R.layout.activity_main);

        lm = (LocationManager) MainActivity.this.getSystemService(Context.LOCATION_SERVICE);

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

        serviceDao = daoSession.getServiceDao();

        // If no trips, go back to log in screen
        if (tripDao.loadAll().size() == 0) {
            Intent intent = new Intent(MainActivity.this, LoadActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
            return;
        }else{
			FragmentTransaction trans = getSupportFragmentManager().beginTransaction();
				/*
				 * IMPORTANT: We use the "root frame" defined in
				 * "root_fragment.xml" as the reference to replace fragment
				 */
			trans.add(R.id.root_fragment, new MyTripFragment());
			//trans.replace(R.id.root_fragment, new MyTripFragment());
			/*
				* IMPORTANT: The following lines allow us to add the fragment
				* to the stack and return to it later, by pressing back
			*/
			trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
			//trans.addToBackStack(null);

			trans.commit();
		}
        
        // Load static variables

        travellerId = travellerInfoDao.loadAll().get(0).getId();

        // Get info from the bundle
		final Bundle bundle = new Bundle();
		Intent intent = getIntent();
		if (intent.hasExtra("travellerId"))
			travellerId = intent.getLongExtra("travellerId", 0L);
		if (intent.hasExtra("eppParkId"))
			eppParkId = intent.getIntExtra("eppParkId", 2);
		if (intent.hasExtra("etpParkId"))
			etpParkId = intent.getIntExtra("etpParkId", 246);

        if(parkInfoDao.loadAll().size() != 0) {
            etpParkId = parkInfoDao.loadAll().get(0).getEtpParkId();
            eppParkId = parkInfoDao.loadAll().get(0).getEppParkId();
        }

		sActivity = this;

		if (!isTablet(this))
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		// Mocklocation stuff
		try {
			LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
			
			boolean isGPSEnabled = false;
			isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
			
			if (!isGPSEnabled) {
				// No network provider is enabled
			}else{
                String mocLocationProvider = LocationManager.GPS_PROVIDER;
                locationManager.addTestProvider(mocLocationProvider, false, false, false, false, true, true, true, 0, 5);
                locationManager.setTestProviderEnabled(mocLocationProvider, true);
                new MockLocationProvider(locationManager, mocLocationProvider).start();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

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

		ImageView logo_esch_sur_sure = (ImageView) findViewById(R.id.logo_esch);
		logo_esch_sur_sure.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				Bundle bundle1 = new Bundle();
				bundle1.putString("nomFragment", "INFO ESCH SUR SURE");
				bundle1.putInt("numFragment", 1);
				PubFragment pubFragment = new PubFragment();
				pubFragment.setArguments(bundle1);

				changeFragment(pubFragment, "esch_sur_sure_fragment");
			}
		});

		// Text view LE PROGRAMME on the footer
		TextView txt_leprogramme = (TextView) findViewById(R.id.txt_leprogramme);
		// Text view App from : CYBERCULTUS on the footer
		TextView txt_cybercultus = (TextView) findViewById(R.id.txt_cybercultus);

		txt_leprogramme.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
			}
		});

		txt_cybercultus.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				Bundle bundle1 = new Bundle();
				bundle1.putString("nomFragment", "INFO CYBERCULTUS");
				bundle1.putInt("numFragment", 2);
				PubFragment pubFragment = new PubFragment();
				pubFragment.setArguments(bundle1);

				changeFragment(pubFragment, "cybercultus_fragment");
			}
		});
    }

    /**
     * function isTablet()
     * @param context
     * @return
     *
     * Check if the device is a tablet
     */
	public static boolean isTablet(Context context) {
		return (context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
	}

	/*
		Change fragment
	 */
	public void changeFragment(Fragment newFragment, String name){
		FragmentManager fm = getSupportFragmentManager();
		if(fm.getBackStackEntryCount() > 0){
			if(fm.getBackStackEntryAt(fm.getBackStackEntryCount()-1).getName() != name){
				FragmentTransaction trans = fm.beginTransaction();

				trans.replace(R.id.root_fragment, newFragment);

				trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
				trans.addToBackStack(name);

				trans.commit();
			}
		}else{
			FragmentTransaction trans = fm.beginTransaction();

			trans.replace(R.id.root_fragment, newFragment);

			trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
			trans.addToBackStack(name);

			trans.commit();
		}
	}

    /**
     * Function onActivityResult()
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 100 && resultCode == RESULT_OK) {

        }
    }
}