package net.ddns.mahaljsp.ch14_03_listfragment;

import android.content.res.Configuration;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
/**
 * Created by Thomas Wu(mahaljsp@gmail.com) on 2016/12/10.
 */
public class MainActivity extends AppCompatActivity {
    static String []movies, details;
    static int position;
    FragmentManager manager;//每次旋轉都會產生新的Activity, 所以要重設manager, 因此不能用static
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(savedInstanceState!=null){
            position=savedInstanceState.getInt("position");
        }
        else{
            movies=getResources().getStringArray(R.array.movies);
            details=getResources().getStringArray(R.array.details);
        }
        manager=getSupportFragmentManager();
        FragmentTransaction transaction=manager.beginTransaction();
        if(getResources().getConfiguration().orientation== Configuration.ORIENTATION_PORTRAIT){
            transaction.replace(R.id.container_portrait, new ListArea(), "ListArea");
        }
        else{
            transaction.replace(R.id.container_landscape_left, new ListArea(), null);
            transaction.replace(R.id.container_landscape_right, new DetailArea(), null);
        }
        transaction.commit();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("position", position);
        super.onSaveInstanceState(outState);
    }
    public void showDetail(int p){
        position=p;
        FragmentTransaction transaction=manager.beginTransaction();
        if(getResources().getConfiguration().orientation==Configuration.ORIENTATION_PORTRAIT){
            transaction.replace(R.id.container_portrait, new DetailArea(), "DetailArea");
        }
        else{
            transaction.replace(R.id.container_landscape_right, new DetailArea(), null);
        }
        transaction.commit();
    }

    @Override
    public void onBackPressed() {
        if(getResources().getConfiguration().orientation==Configuration.ORIENTATION_PORTRAIT
                && manager.findFragmentByTag("DetailArea")!=null){
            FragmentTransaction transaction=manager.beginTransaction();
            transaction.replace(R.id.container_portrait, new ListArea(), "ListArea");
            transaction.commit();
        }
        else {
            super.onBackPressed();
        }
    }
}
