package com.netfluke.sergey.catpicker;

/**
 *   This example is different from the Android FragmentBasics in
 *        https://developer.android.com/training/basics/fragments/index.html
 *     in that the intent here is to programmatically present different views in
 *     different screen orientations: one fragment in portrait, two side-by-side in landscape.
 *
 *   In this example, the fragments are created automatically by calling
 *         setContentView(R.layout.activity_main);
 *   The trick is to supply two version of this file, in specially named res/ directories,
 *     layout-land and layout-port. These layouts directly specify the fragments
 *     to be instantiated into the layout, and the internal logic of setContentView(..)
 *     picks the right variant for the current screen orientation. See CatPicker for
 *     how this can be done programmatically.
 *
 *   This version does not use SharedPreferences, so it must take extra care
 *      to preserve state between flips, and the choice of cat is not
 *      remembered between restarts.
 */

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

public class MainActivity extends AppCompatActivity {

    private int catId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Log.d("MAIN", "onCreate( " +
                ((savedInstanceState == null) ?
                        "null )" : savedInstanceState.toString() + " )"));

        // picks either portrait or landscape variant, res/layout-land/activity_main.xml
        //  or res/layout-port/activity_main.xml based on the screen orientation at the moment.
        setContentView(R.layout.activity_main);

        FragmentManager fmgr = getFragmentManager();
        ImageFragment im = (ImageFragment) fmgr.findFragmentById(R.id.image_fragment);

        if (im != null) {  // we are in landscape mode
            if (savedInstanceState != null)
                im.catId = savedInstanceState.getInt("CAT_ID", R.drawable.pusheen1);
            else
                im.catId = R.drawable.pusheen1;  // default cat
        }
        else {
            Log.d("MAIN", "No image fragment");
        }
    }

    /**
     *    Calls to super purposefully disabled. We don't want the Views saved
     *       and restored, we re-create them manually. Using these super calls
     *       results in fragment duplication (see that with
     *         "abd shell dumpsys activity <package name>").
     *    So we save only what we want to save. Cf.
     *    https://www.intertech.com/Blog/saving-and-retrieving-android-instance-state-part-1/
     *    https://www.intertech.com/Blog/saving-and-retrieving-android-instance-state-part-2/
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        //super.onSaveInstanceState(outState);
        Log.d("STATE", "onSaveInstanceState");
        outState.putInt("CAT_ID", catId);
    }

    //  See above
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        //super.onRestoreInstanceState(savedInstanceState);
        Log.d("STATE", "onRestoreInstanceState" + savedInstanceState.toString());
        catId = savedInstanceState.getInt("CAT_ID");

        // should restore this to image fragment if any
        ImageFragment im = (ImageFragment) getFragmentManager().findFragmentById(R.id.image_fragment);
        if( im != null )
            im.catId = catId;
    }

    public void click(View v){

        // which button?
        switch( v.getId() ){
            case R.id.button1:
                catId = R.drawable.manul1;
                break;
            case R.id.button2:
                catId = R.drawable.manul2;
                break;
            case R.id.button3:
                catId = R.drawable.manul3;
                break;
            default:
                Log.d("MAIN", "no such cat");
                catId = R.drawable.pusheen1;
        }

        // Set image in ImageFragment; instantiate it if necessary
        ImageFragment imgFrag = (ImageFragment) getFragmentManager().findFragmentById(R.id.image_fragment);
        if( imgFrag != null ){  // we are likely in landscape mode
            Log.d("MAIN", "located image fragment");

            // the fragment may exist, but not visible. Check it.
            if( imgFrag.isVisible())
                // We are in landscape. Change the pic in visible image fragment
                imgFrag.loadPicture(catId);
            else {
                // Unlikely. Does this ever happen?
                Log.d("MAIN", "image fragment exists but isn't visible. Shouldn't happen.");
            }
        }
        else{  // no ImageFragment; we must be in portrait mode; replace picker with a new image
            Log.d("MAIN", "ImageFragment not found by tag; re-creating.");
            // create a new image fragment
            imgFrag =  new ImageFragment();
            imgFrag.catId = catId;   // to be displayed in ImageFragment's  onResume()

            FragmentTransaction t = getFragmentManager().beginTransaction();
            t.replace(R.id.content_frame, imgFrag, "image");

            // Back-ing out of this image view should restore the picker view, so save it to backstack.
            t.addToBackStack(null);

            t.commit();
            getFragmentManager().executePendingTransactions();
        }
    }
}
