package it.devapp.esempioandroidfragment;

import android.support.v4.app.*;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;

import it.devapp.esempioandroidfragment.fragments.CittaFragment;
import it.devapp.esempioandroidfragment.fragments.MainFragment;

public class MainActivity extends AppCompatActivity {

    private ElencoCitta elenco;

    @Override
    public void onBackPressed() {
        getSupportActionBar().setDisplayHomeAsUpEnabled(false);
        super.onBackPressed();
    }

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

        elenco=new ElencoCitta();

        FragmentManager fm = getSupportFragmentManager();
        Fragment trovato=fm.findFragmentByTag(CittaFragment.CITTAFRAGMENT_TAG);

        FragmentTransaction ft = fm.beginTransaction();
        if (trovato!=null) {
            ft.replace(R.id.fragment, trovato);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        else
            ft.replace(R.id.fragment, new MainFragment());
        ft.commit();
    }


    public void cambiaFragment(View v)
    {
        CittaFragment fragment=null;
        switch(v.getId())
        {
            case R.id.roma:
                fragment=CittaFragment.newInstance(elenco.trovaCitta("roma"));
                break;
            case R.id.milano:
                fragment=CittaFragment.newInstance(elenco.trovaCitta("milano"));
                break;
            case R.id.palermo:
                fragment=CittaFragment.newInstance(elenco.trovaCitta("palermo"));
        }
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.addToBackStack(null);
        ft.replace(R.id.fragment, fragment,CittaFragment.CITTAFRAGMENT_TAG);
        ft.commit();

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                getSupportFragmentManager().popBackStack();
                getSupportActionBar().setDisplayHomeAsUpEnabled(false);
                break;
        }
        return false;
    }

}
