cat.wuyingren.rorhelper.activities.MainActivity.java Source code

Java tutorial

Introduction

Here is the source code for cat.wuyingren.rorhelper.activities.MainActivity.java

Source

/** Copyright (c) 2014 Jordi Lpez <@wuyingren>
 *
 * MIT License:
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 */
package cat.wuyingren.rorhelper.activities;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.getbase.floatingactionbutton.FloatingActionButton;
import com.getbase.floatingactionbutton.FloatingActionsMenu;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;

import cat.wuyingren.rorhelper.R;
import cat.wuyingren.rorhelper.fragments.CardListFragment;
import cat.wuyingren.rorhelper.fragments.GameFactionFragment;
import cat.wuyingren.rorhelper.fragments.GameListFragment;
import cat.wuyingren.rorhelper.fragments.GameStatusFragment;
import cat.wuyingren.rorhelper.fragments.dialogs.ConfirmationDialogFragment;
import cat.wuyingren.rorhelper.fragments.dialogs.DeleteGameDialogFragment;
import cat.wuyingren.rorhelper.fragments.dialogs.ManageSenatorDialogFragment;
import cat.wuyingren.rorhelper.fragments.dialogs.NewGameDialogFragment;
import cat.wuyingren.rorhelper.fragments.dialogs.NextPhaseDialogFragment;
import cat.wuyingren.rorhelper.profiles.CardDecks;
import cat.wuyingren.rorhelper.profiles.Faction;
import cat.wuyingren.rorhelper.profiles.Game;
import cat.wuyingren.rorhelper.profiles.ManageSenatorResult;
import cat.wuyingren.rorhelper.profiles.NavigationDrawerElement;
import cat.wuyingren.rorhelper.profiles.NewGameResult;
import cat.wuyingren.rorhelper.profiles.Senator;
import cat.wuyingren.rorhelper.profiles.Statesman;
import cat.wuyingren.rorhelper.sql.GameDataSource;
import cat.wuyingren.rorhelper.utils.NavigationDrawerAdapter;

public class MainActivity extends ActionBarActivity implements NewGameDialogFragment.NewGameDialogListener,
        GameListFragment.GameListFragmentListener, NextPhaseDialogFragment.NextPhaseDialogListener,
        DeleteGameDialogFragment.DeleteGameDialogListener, ManageSenatorDialogFragment.ManageSenatorDialogListener {

    private Toolbar toolbar;
    private static Context context;

    private DrawerLayout mDrawerLayout;
    private ActionBarDrawerToggle mDrawerToggle;

    private String mTitle;
    private String mDrawerTitle;
    private ListView mDrawerList;

    private static GameDataSource dataSource;
    private Game currentGame;
    private long currentGameId;

    private ProgressDialog pDialog;

    private final String GAME_ID = "gameid";

    private Map<String, Senator> senatorMap = new HashMap<String, Senator>();
    private Map<String, Statesman> statesmanMap = new HashMap<String, Statesman>();
    private int scenario = 0;
    private SharedPreferences prefs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
        }

        prefs = PreferenceManager.getDefaultSharedPreferences(this);

        dataSource = new GameDataSource(this);
        dataSource.open();

        initializeDrawer();
        initializeActionsButton();

        refreshDrawer(R.array.sections);

        // Choose first item by default
        selectItem(0);

    }

    private void initializeDrawer() {

        mTitle = mDrawerTitle = getTitle().toString();

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.sectionList_game);

        // Set the list's click listener
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.navigation_drawer_open,
                R.string.navigation_drawer_close) {
            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                getSupportActionBar().setTitle(mTitle);
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                getSupportActionBar().setTitle(mDrawerTitle);
            }

        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
    }

    private void initializeActionsButton() {
        FloatingActionsMenu actionsMenu = (FloatingActionsMenu) findViewById(R.id.multiple_actions);
        FloatingActionButton actionNextPhase = (FloatingActionButton) findViewById(R.id.fab_action_nextphase);
        FloatingActionButton actionKillSenator = (FloatingActionButton) findViewById(R.id.fab_action_killsenator);
        FloatingActionButton actionAddSenator = (FloatingActionButton) findViewById(R.id.fab_action_addsenator);
        FloatingActionButton actionAddStatesman = (FloatingActionButton) findViewById(R.id.fab_action_addstatesman);

        actionNextPhase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                goToNextPhase();
            }
        });

        actionKillSenator.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showManageSenatorDialog(true, false);
            }
        });

        actionAddSenator.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showManageSenatorDialog(false, false);
            }
        });

        actionAddStatesman.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showManageSenatorDialog(false, true);
            }
        });

        if (prefs.getBoolean(SettingsActivity.KEY_PREF_UI_FLOATINGACTIONMENU, false)) {
            actionsMenu.setVisibility(View.VISIBLE);
        } else {
            actionsMenu.setVisibility(View.GONE);
        }
    }

    private void refreshDrawer(int arrayID) {

        ArrayList<NavigationDrawerElement> elements = new ArrayList<NavigationDrawerElement>();
        elements.add(new NavigationDrawerElement(0, getString(R.string.title_sectiongroup1), true));
        elements.add(new NavigationDrawerElement(0, getString(R.string.title_section1), false));
        elements.add(new NavigationDrawerElement(0, getString(R.string.title_section2), false));
        elements.add(new NavigationDrawerElement(0, getString(R.string.title_sectiongroup2), true));
        if (arrayID == R.array.sections_1p || arrayID == R.array.sections_2p) {
            for (String key : getResources().getStringArray(arrayID)) {
                elements.add(new NavigationDrawerElement(0, key, false));
            }

            if (prefs.getBoolean(SettingsActivity.KEY_PREF_EXTRA_INITIALCARDS, false)) {
                elements.add(new NavigationDrawerElement(0, getString(R.string.title_sectiongroup3), true));
                elements.add(new NavigationDrawerElement(0, getString(R.string.title_section3), false));
                elements.add(new NavigationDrawerElement(0, getString(R.string.title_section4), false));
            }
        }

        // Set the adapter for the list view
        mDrawerList
                .setAdapter(new NavigationDrawerAdapter(this, R.layout.simple_list_item_activated_1_ror, elements));

        /*mDrawerList.setAdapter(ArrayAdapter.createFromResource(this, arrayID,
            R.layout.simple_list_item_activated_1_ror));*/

    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    public static Context getContext() {
        return context;
    }

    public static GameDataSource getDataSource() {
        if (dataSource == null) {
            dataSource = new GameDataSource(context);
            dataSource.open();
        }
        return dataSource;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        if (prefs.getBoolean(SettingsActivity.KEY_PREF_UI_FLOATINGACTIONMENU, false)) {
            getMenuInflater().inflate(R.menu.menu_main_fab, menu);
        } else {
            getMenuInflater().inflate(R.menu.menu_main_complete, menu);
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Pass the event to ActionBarDrawerToggle, if it returns
        // true, then it has handled the app icon touch event
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        switch (id) {
        case R.id.action_settings:
            Intent i = new Intent(context, SettingsActivity.class);
            startActivity(i);
            return true;
        case R.id.action_new:
            NewGameDialogFragment dialog = new NewGameDialogFragment();
            dialog.show(getSupportFragmentManager(), "");
            return true;
        case R.id.action_nextphase:
            goToNextPhase();
            return true;
        case R.id.action_delete:
            if (currentGame == null) {
                Toast.makeText(getContext(), getString(R.string.no_game), Toast.LENGTH_LONG).show();
            } else {
                DeleteGameDialogFragment del_dialog = new DeleteGameDialogFragment();
                showConfirmationDialog(getString(R.string.dialog_confirmation_delete),
                        getString(R.string.action_delete), del_dialog);
            }
            return true;
        case R.id.action_killsenator:
            showManageSenatorDialog(true, false);
            return true;
        case R.id.action_addsenator:
            showManageSenatorDialog(false, false);
            return true;
        case R.id.action_addstatesman:
            showManageSenatorDialog(false, true);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }

    }

    private void showManageSenatorDialog(boolean kill, boolean statesman) {

        if (isActionPossible()) {
            ManageSenatorDialogFragment dialog = new ManageSenatorDialogFragment();

            Bundle args = new Bundle();
            args.putBoolean(ManageSenatorDialogFragment.ARG_MODE, kill);
            args.putBoolean(ManageSenatorDialogFragment.ARG_TYPE, statesman);
            args.putLong(ManageSenatorDialogFragment.ARG_GAMEID, currentGameId);
            if (!kill) {
                String[] keys;
                ArrayList<String> values = new ArrayList<String>();
                if (statesman) {
                    keys = new String[statesmanMap.size()];
                    keys = statesmanMap.keySet().toArray(keys);

                    for (String key : keys) {
                        values.add(statesmanMap.get(key).getName());
                    }
                } else {
                    keys = new String[senatorMap.size()];
                    keys = senatorMap.keySet().toArray(keys);

                    for (String key : keys) {
                        values.add(senatorMap.get(key).getName());
                    }
                }

                args.putStringArray(ManageSenatorDialogFragment.ARG_ARRAY, keys);
                args.putStringArrayList(ManageSenatorDialogFragment.ARG_VALUES, values);
            }
            dialog.setArguments(args);
            dialog.show(getSupportFragmentManager(), "");
        }
    }

    private void goToNextPhase() {
        if (currentGame == null) {
            Toast.makeText(getContext(), getString(R.string.no_game), Toast.LENGTH_LONG).show();
        } else {
            NextPhaseDialogFragment dialog = new NextPhaseDialogFragment();

            if (currentGame.getTurn() == 0) {
                showConfirmationDialog(getString(R.string.dialog_confirmation_startgame),
                        getString(R.string.dialog_confirmation_nextphase), dialog);
                //initializeGame();
                //refresh();
            } else {
                String phase = Game.getPhaseName(currentGame.getPhase() + 1, this.getResources());
                showConfirmationDialog(phase, getString(R.string.dialog_confirmation_nextphase), dialog);
            }
        }
    }

    private void showConfirmationDialog(String message, String title, ConfirmationDialogFragment dialog) {
        //ConfirmationDialogFragment dialog = new ConfirmationDialogFragment();
        Bundle args = new Bundle();
        args.putString(ConfirmationDialogFragment.ARG_MESSAGE, message);
        args.putString(ConfirmationDialogFragment.ARG_TITLE, title);
        dialog.setArguments(args);
        dialog.show(getSupportFragmentManager(), "");
    }

    private boolean isActionPossible() {
        if (currentGame == null) {
            Toast.makeText(getContext(), getString(R.string.no_game), Toast.LENGTH_LONG).show();
            return false;
        } else if (dataSource.getAllFactions(currentGameId).size() == 0) {
            Toast.makeText(getContext(), getString(R.string.nofactions), Toast.LENGTH_LONG).show();
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void onNewGameDialogClick(NewGameResult result) {
        Log.w("TAG", result.toString());
        dataSource.createGame(result.getName(),
                getResources().getStringArray(R.array.scenariolist)[result.getScenario()], result.getPlayers() + 1,
                result.getScenario());
        refresh();
    }

    private void refresh() {
        selectItem(mDrawerList.getCheckedItemPosition());
    }

    @Override
    public void onGameListItemClick(long id) {
        Log.w("TAG", "game clicked " + id);
        currentGameId = id;
        currentGame = dataSource.getGameById(id);
        if (currentGame.getPlayers() == 1) {
            refreshDrawer(R.array.sections_1p);
        } else {
            refreshDrawer(R.array.sections_2p);
        }

        senatorMap.clear();
        statesmanMap.clear();

        senatorMap.putAll(CardDecks.getScenarioSenatorDeckMap(scenario));
        statesmanMap.putAll(CardDecks.getScenarioStatesmanDeckMap(scenario));
        ArrayList<Faction> factions = dataSource.getAllFactions(currentGameId);
        Iterator<Faction> ite = factions.iterator();
        if (ite.hasNext()) {
            while (ite.hasNext()) {
                Faction f = ite.next();
                f.setUpGuideParameters(getResources());
                Iterator<Senator> ite2 = dataSource.getAllSenatorsOfFaction(f.getId()).iterator();
                while (ite2.hasNext()) {
                    Senator s = ite2.next();
                    if (s instanceof Statesman) {
                        Statesman st = (Statesman) s;
                        statesmanMap.remove(st.getIdComplete());
                    } else {
                        int ids = s.getId();
                        senatorMap.remove(String.valueOf(ids));
                    }
                    dataSource.checkSenatorAvailability(s, currentGameId);
                }
                //Refresh fragment data
                //  refreshFactionFragmentData(f.getName(), f.getId());

            }
        }
    }

    /*@Override
    public void onMultipleItemsDeletion() {
    Log.w("TAG", "deleting...");
        
    }*/

    @Override
    public void onNextPhaseDialogPositiveClick() {
        switch (currentGame.getTurn()) {
        case 0:
            currentGame.setTurn(1);
            //initializeGame();
            InitializeGameTask task = new InitializeGameTask();
            task.execute();
            break;
        default:
            currentGame.setPhase(currentGame.getPhase() + 1);
            if (currentGame.getPhase() >= 7) {
                currentGame.setTurn(currentGame.getTurn() + 1);
                currentGame.setPhase(0);
            }
            break;
        }
        dataSource.updateGame(currentGame);

        refresh(); //refresh
        if (prefs.getBoolean(SettingsActivity.KEY_PREF_GENERAL_AUTOCALC, true)) {
            checkPhaseTasks(currentGame.getPhase());
        }

    }

    private void checkPhaseTasks(int phase) {
        switch (phase) {
        case 1: // Income phase
            ArrayList<Faction> list = dataSource.getAllFactions(currentGameId);
            Iterator<Faction> ite = list.iterator();
            while (ite.hasNext()) {
                Faction f = ite.next();
                ArrayList<Senator> sen = f.calculateIncome(dataSource.getAllSenatorsOfFaction(f.getId()),
                        getResources());
                dataSource.updateSenatorList(sen, currentGameId);
                dataSource.updateFaction(f, currentGameId);
            }
            break;
        case 3: // Plebs phase

            break;
        }
    }

    private ArrayList<Senator> drawSenators(int quantity, Map<String, Senator> senatorMap, long factionID) {
        Random r = new Random();
        ArrayList<Senator> fam = new ArrayList<Senator>();
        while (fam.size() < quantity) {
            Object[] keys = senatorMap.keySet().toArray();
            Object key = keys[r.nextInt(keys.length)];
            if (senatorMap.get(key) != null) {
                Senator s = dataSource.createSenator(senatorMap.get(key), factionID, currentGameId);
                senatorMap.remove(String.valueOf(key));
                fam.add(s);
            }
        }
        //dataSource.updateFaction(factionID, currentGameId);
        return fam;
    }

    @Override
    public void onDeleteGameDialogPositiveClick() {
        DeleteGameTask task = new DeleteGameTask();
        task.execute(currentGameId);
    }

    @Override
    public void onManageSenatorDialogPositiveClick(ManageSenatorResult result) {
        Log.w("TAG", result.toString());
        if (result.isKill()) { // Killing
            long senatorID = 0;
            if (result.isRandomKill()) {
                Object[] keys = senatorMap.keySet().toArray();

                int key = new Random().nextInt(keys.length) + 1;
                Toast.makeText(context, getString(R.string.dialog_managesenator_kill_title) + " " + key,
                        Toast.LENGTH_SHORT).show();
                senatorID = key;
            } else {
                if (result.isStatesman()) {
                    senatorID = Long
                            .valueOf(result.getSenatorID().substring(0, result.getSenatorID().length() - 1));
                } else {
                    senatorID = Long.valueOf(result.getSenatorID());
                }
            }
            Log.w("TAG", "Will try to kill " + senatorID);

            try {
                long res = dataSource.deleteSenator(senatorID, currentGame);
                if (res == -1) { // No senator found
                    Toast.makeText(this, R.string.invalid_id, Toast.LENGTH_SHORT).show();
                } else {
                    Senator s = dataSource.getSenatorById(res);
                    if (!s.isStatesman()) {
                        // Restore in the array so it can be chosen again
                        senatorMap.put(String.valueOf(s.getId()),
                                CardDecks.getScenarioSenatorDeckMap(scenario).get(s.getId()));
                        refresh();
                    }
                }
            } catch (NumberFormatException e) {
                Toast.makeText(MainActivity.getContext(), getString(R.string.invalid_id), Toast.LENGTH_SHORT)
                        .show();
            }
        } else { // Adding

            if (result.isStatesman()) {
                String index = result.getSenatorID().substring(0, result.getSenatorID().length() - 1);
                if (senatorMap.containsKey(index)) {
                    dataSource.createSenator(senatorMap.get(index), result.getFactionID(), currentGameId);
                    senatorMap.remove(index);
                }
                dataSource.createStatesman(statesmanMap.get(result.getSenatorID()), result.getFactionID(),
                        currentGameId);
                statesmanMap.remove(result.getSenatorID());

            } else {
                dataSource.createSenator(senatorMap.get(result.getSenatorID()), result.getFactionID(),
                        currentGameId);
                senatorMap.remove(result.getSenatorID());
            }
        }
        refresh();
    }

    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView parent, View view, int position, long id) {
            selectItem(position);
        }
    }

    private Fragment prepareFactionFragment(long factionID) {
        Fragment fragment = new GameFactionFragment();
        Bundle args = new Bundle();
        args.putLong(GameFactionFragment.ARG_GAME_ID, currentGameId);
        args.putLong(GameFactionFragment.ARG_FACTION_ID, factionID);
        fragment.setArguments(args);
        return fragment;
    }

    /** Swaps fragments in the menu_main_complete content view */
    private void selectItem(int position) {
        Fragment fragment = new GameListFragment();
        Bundle args = new Bundle();
        switch (position) {
        case 0:
        case 3:
        case 8:
            //Headers
            break;
        case 1:
            mTitle = getString(R.string.title_section1);
            fragment.setArguments(args);
            break;
        case 2:
            mTitle = getString(R.string.title_section2);
            fragment = new GameStatusFragment();
            args = new Bundle();
            args.putLong(GameStatusFragment.ARG_GAME_ID, currentGameId);
            fragment.setArguments(args);
            break;
        case 4:
            mTitle = getString(R.string.faction_imperials);
            fragment = prepareFactionFragment(dataSource.getFactionId(currentGameId, mTitle));
            break;
        case 5:
            mTitle = getString(R.string.faction_plutocrats);
            fragment = prepareFactionFragment(dataSource.getFactionId(currentGameId, mTitle));
            break;
        case 6:
            mTitle = getString(R.string.faction_conservatives);
            fragment = prepareFactionFragment(dataSource.getFactionId(currentGameId, mTitle));
            break;
        case 7:
            mTitle = getString(R.string.faction_populists);
            fragment = prepareFactionFragment(dataSource.getFactionId(currentGameId, mTitle));
            break;

        case 9:
            mTitle = getString(R.string.title_section3);
            fragment = new CardListFragment();
            args = new Bundle();
            args.putInt(CardListFragment.ARG_SCENARIO_ID, currentGame.getScenarioID());
            args.putBoolean(CardListFragment.ARG_STATEMEN_ENABLED, false);
            fragment.setArguments(args);
            break;
        case 10:
            mTitle = getString(R.string.title_section4);
            fragment = new CardListFragment();
            args = new Bundle();
            args.putInt(CardListFragment.ARG_SCENARIO_ID, currentGame.getScenarioID());
            args.putBoolean(CardListFragment.ARG_STATEMEN_ENABLED, true);
            fragment.setArguments(args);
            break;
        default:
            break;
        }

        // Insert the fragment by replacing any existing fragment
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

        // Highlight the selected item, update the title, and close the drawer
        mDrawerList.setItemChecked(position, true);
        //getActionBar().setTitle((mOperationsSystem[position]));
        mDrawerLayout.closeDrawer(mDrawerLayout.findViewById(R.id.drawerRoot));
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title.toString();
        getSupportActionBar().setTitle(mTitle);
    }

    private class DeleteGameTask extends AsyncTask<Long, Long, Void> {

        @Override
        protected Void doInBackground(Long... longs) {
            for (long l : longs) {
                dataSource.deleteGameById(l);
            }

            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(getContext());
            pDialog.setMessage(getString(R.string.pDialog_game_deleting));
            pDialog.show();
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            pDialog.setMessage(getString(R.string.pDialog_game_done));
            pDialog.dismiss();
            //uncompleteSlider();
            refresh();
            refreshDrawer(R.array.sections);
            currentGame = null;
        }
    }

    private class InitializeGameTask extends AsyncTask<Void, Long, Void> {

        @Override
        protected Void doInBackground(Void... voids) {
            initializeGame();
            return null;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(getContext());
            pDialog.setMessage(getString(R.string.pDialog_game_updating));
            pDialog.show();
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);
            pDialog.setMessage(getString(R.string.pDialog_game_done));
            pDialog.dismiss();
            refresh(); // refresh
        }

        private void initializeGame() {
            senatorMap = new HashMap<String, Senator>();
            senatorMap.putAll(CardDecks.getScenarioSenatorDeckMap(scenario));

            initializeFactions(currentGame.getPlayers(), senatorMap);

            /*ArrayList<Faction> facList = dataSource.getAllFactions(currentGameId);
            for(Faction f : facList) {
            refreshFactionFragmentData(f.getName(), f.getId());
            }*/
        }

        private void initializeFactions(int numplayers, Map<String, Senator> senatorMap) {

            int neutrals = 3;
            if (numplayers == 1) {
                neutrals = 4;
            }
            while (neutrals > 0) {
                Faction f = dataSource.createFaction(currentGameId);
                if (prefs.getBoolean(SettingsActivity.KEY_PREF_GENERAL_INITFACTIONS, true)) {
                    drawSenators(3, senatorMap, f.getId());
                }
                //f.setFamilies(fam);
                neutrals--;
            }
            ArrayList<Faction> tmp = dataSource.setFactionNames(currentGameId,
                    getResources().getStringArray(R.array.faction_nameID));
            if (prefs.getBoolean(SettingsActivity.KEY_PREF_GENERAL_INITFACTIONS, true)) {
                // 2 additional senators for Conservatives
                drawSenators(2, senatorMap, tmp.get(tmp.size() - 1).getId());

                if (tmp.size() > 3) {
                    // 1 additional senator for Populists
                    drawSenators(1, senatorMap, tmp.get(tmp.size() - 2).getId());
                }
            }
        }

    }
}