/*******************************************************************************
 * ADOBE CONFIDENTIAL
 *  ___________________
 *
 *  Copyright 2014 Adobe Systems Incorporated
 *  All Rights Reserved.
 *
 *  NOTICE:  All information contained herein is, and remains
 *  the property of Adobe Systems Incorporated and its suppliers,
 *  if any.  The intellectual and technical concepts contained
 *  herein are proprietary to Adobe Systems Incorporated and its
 *  suppliers and are protected by trade secret or copyright law.
 *  Dissemination of this information or reproduction of this material
 *  is strictly forbidden unless prior written permission is obtained
 *  from Adobe Systems Incorporated.
 ******************************************************************************/

package com.adobe.primetime.reference.ui.entitlement;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import com.adobe.adobepass.accessenabler.models.Mvpd;
import com.adobe.primetime.reference.PrimetimeReference;
import com.adobe.primetime.reference.R;
import com.adobe.primetime.reference.entitlement.AccessEnablerDelegate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class MvpdPickerActivity extends AppCompatActivity implements IMvpdPickerClickListener
{
    /**
     * Intent extra key for selected provider passed by activity's result
     */
    public static final String EXTRA_MVPD = "extra_mvpd";

    private static final String LOG_TAG = PrimetimeReference.LOG_APP_NAME + "MvpdPickerActivity";

    // full list of MVPDs
    private final ArrayList<MvpdListItem> mvpdList = new ArrayList<MvpdListItem>();

    // the current fragment view to display
    private MvpdPickerFragment.ViewType currentView;
    private static final String SAVED_VIEW_TYPE = "fragment_view_type";

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

        if (savedInstanceState != null && savedInstanceState.containsKey(SAVED_VIEW_TYPE))
        {
            currentView = (MvpdPickerFragment.ViewType) savedInstanceState.getSerializable(SAVED_VIEW_TYPE);
        }
        else
        {
            // default to Grid view
            currentView = MvpdPickerFragment.ViewType.GRID;
        }

        setTitle(R.string.entitlement_picker_activity_title);

        setContentView(R.layout.entitlement_picker_activity);

        Bundle bundle = getIntent().getBundleExtra(AccessEnablerDelegate.BUNDLED_MVPD_DATA);
        ArrayList<String> serializedData = bundle.getStringArrayList(AccessEnablerDelegate.BUNDLED_MVPD_DATA);

        try
        {
            for (String item : serializedData)
            {
                mvpdList.add(new MvpdListItem(Mvpd.deserialze(item)));
            }
        }
        catch (Exception e)
        {
            PrimetimeReference.logger.e(LOG_TAG + "#handleIntent",
                    "Exception while deserializing list items from Bundle. " + e.getMessage());
        }

        // sort the list by display name
        Collections.sort(mvpdList, new MvpdNameComparator());

        // add fragment which displays MVPDs to ViewGroup
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        MvpdPickerFragment fragment = MvpdPickerFragment.newInstance(currentView, mvpdList);
        fragmentTransaction.replace(R.id.container, fragment, currentView.name());
        fragmentTransaction.commit();

    }

    @Override
    protected void onSaveInstanceState(Bundle outState)
    {
        // save the currently selected fragment view
        outState.putSerializable(SAVED_VIEW_TYPE, currentView);
        super.onSaveInstanceState(outState);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();

        inflater.inflate(R.menu.actionbar_entitlement_picker, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {

            case R.id.ActionBarAbout:
                PrimetimeReference.logger.i(LOG_TAG + "#onOptionsItemSelected",
                        "About action bar item activated.");
                PrimetimeReference.showAbout(this);
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }

    /**
     * Handle an item selection from the MVPD picker fragment. The selected item
     * is returned to the calling activity while this activity is finished.
     * @param item The item selected
     *
     * @see com.adobe.primetime.reference.ui.entitlement.IMvpdPickerClickListener
     */
    @Override
    public void handleItemSelection(Object item) {
        Intent result = new Intent();

        if (item != null && item instanceof  MvpdListItem)
        {
            com.adobe.adobepass.accessenabler.models.Mvpd mvpd = ((MvpdListItem) item).getMvpd();
            result.putExtra(EXTRA_MVPD, mvpd.getId());
        }

        setResult(RESULT_OK, result);
        finish();
    }

    /**
     * Handle a view change from the MVPD picker fragment. Detaches the current fragment in view
     * and attaches a fragment for the {@code newView}. If a fragment which implements the {@code newView}
     * doesn't exist, a new instance is created and attached to this activitiy's view.
     *
     * @param newView The new view type for the fragment
     *
     * @see com.adobe.primetime.reference.ui.entitlement.IMvpdPickerClickListener
     */
    @Override
    public void handleViewChange(MvpdPickerFragment.ViewType newView) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        switch (newView)
        {
            case GRID:
                fragmentTransaction.setCustomAnimations(R.anim.abc_fade_in, R.anim.abc_slide_out_bottom);
                break;

            case LIST:
                fragmentTransaction.setCustomAnimations(R.anim.abc_slide_in_bottom, R.anim.abc_fade_out);
                break;
        }

        // find existing fragment and detach it
        MvpdPickerFragment fragment = (MvpdPickerFragment) fragmentManager.findFragmentById(R.id.container);
        if (fragment != null)
        {
            fragmentTransaction.detach(fragment);
        }

        // now get/create fragment for new view
        fragment = (MvpdPickerFragment) fragmentManager.findFragmentByTag(newView.name());

        if (fragment == null)
        {
            fragment = MvpdPickerFragment.newInstance(newView, mvpdList);
            fragmentTransaction.add(R.id.container, fragment, newView.name());
        }
        else
        {
            fragmentTransaction.attach(fragment);
        }

        fragmentTransaction.commit();

        this.currentView = newView;
    }

    private class MvpdNameComparator implements Comparator<MvpdListItem>
    {

        @Override
        public int compare(MvpdListItem lhs, MvpdListItem rhs) {
            return lhs.getMvpd().getDisplayName().compareTo(rhs.getMvpd().getDisplayName());
        }
    }
}
