fr.eoit.activity.fragment.blueprint.InventionFragment.java Source code

Java tutorial

Introduction

Here is the source code for fr.eoit.activity.fragment.blueprint.InventionFragment.java

Source

/**
 * Copyright (C) 2012 Picon software
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
    
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
package fr.eoit.activity.fragment.blueprint;

import android.content.BroadcastReceiver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.util.FloatMath;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import fr.eoit.R;
import fr.eoit.activity.util.BlueprintUtil;
import fr.eoit.activity.util.PricesUtils;
import fr.eoit.db.bean.Blueprint;
import fr.eoit.db.bean.Prices;
import fr.eoit.formula.FormulaCalculator;
import fr.eoit.formula.util.DecryptorUtil;
import fr.eoit.formula.util.DecryptorUtil.DecryptorBonuses;
import fr.eoit.service.updater.PriceUpdaterService;
import fr.piconsoft.activity.fragment.LoaderFragment;
import fr.piconsoft.db.util.DbUtil;

import java.text.DecimalFormat;
import java.text.NumberFormat;

/**
 * @author picon.software
 *
 */
public class InventionFragment extends LoaderFragment<Cursor> {

    private final static NumberFormat nfPercent = new DecimalFormat("##0.##%");

    private TextView inventionChancesTextView, costTextView, profitTextView;

    private int blueprintId = -1, parentTypeId, producedItemId, producedItemGroupId, decryptorId;
    private short metaLevel;

    private DecryptorBonuses currentDecryptorBonuses = DecryptorUtil.NO_DECRYPTOR;

    private short encryptionSkillLevel, datacore1SkillLevel, datacore2SkillLevel;
    private double singleBlueprintCopyPrice, blueprintTotalCost, producePrice;
    private float inventionChances;
    private int numberOfChances;

    private RequiredSkillInventionFragment requiredSkillInventionFragment;
    private RequiredItemsInventionFragment requiredItemsInventionFragment;
    private RequiredDecryptorFragment requiredDecryptorFragment;

    private PriceChangedBroadCastReceiver receiver = new PriceChangedBroadCastReceiver();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View fragment = inflater.inflate(R.layout.blueprint_invention, container, false);

        inventionChancesTextView = (TextView) fragment.findViewById(R.id.INVENTION_CHANCES);
        costTextView = (TextView) fragment.findViewById(R.id.COST_VALUE);
        profitTextView = (TextView) fragment.findViewById(R.id.PROFIT_VALUE);

        blueprintId = getArguments().getInt("blueprintId");
        producedItemId = getArguments().getInt("produceItemId");
        producedItemGroupId = getArguments().getInt("groupId");

        requiredSkillInventionFragment = (RequiredSkillInventionFragment) getFragmentManager()
                .findFragmentById(R.id.REQUIRED_SKILLS_FRAGMENT);
        requiredItemsInventionFragment = (RequiredItemsInventionFragment) getFragmentManager()
                .findFragmentById(R.id.REQUIRED_ITEMS_FRAGMENT);
        requiredDecryptorFragment = (RequiredDecryptorFragment) getFragmentManager()
                .findFragmentById(R.id.REQUIRED_DECRYPTOR_FRAGMENT);

        inventionChancesTextView.setText(
                nfPercent.format(FormulaCalculator.getBaseInventionChances(producedItemId, producedItemGroupId)));

        initOrRestart();

        return fragment;
    }

    @Override
    protected Loader<Cursor> getCursorLoader(int id, Bundle args) {
        return new CursorLoader(getActivity(),
                ContentUris.withAppendedId(Blueprint.CONTENT_ID_URI_BASE, blueprintId),
                new String[] { Blueprint._ID, Blueprint.COLUMN_NAME_PARENT_TYPE_ID,
                        Blueprint.COLUMN_NAME_INVENTION_ITEM_META_LEVEL, Blueprint.COLUMN_NAME_DECRYPTOR_ID,
                        Blueprint.COLUMN_NAME_ML, Blueprint.COLUMN_NAME_PL, Blueprint.COLUMN_NAME_PRODUCE_ITEM_ID,
                        Blueprint.COLUMN_NAME_UNIT_PER_BATCH, Blueprint.COLUMN_NAME_PRODUCTION_TIME,
                        Blueprint.COLUMN_NAME_PRODUCTIVITY_MODIFIER, Blueprint.COLUMN_NAME_TECH_LEVEL,
                        Blueprint.COLUMN_NAME_MAX_PRODUCTION_LIMIT, Blueprint.COLUMN_NAME_RESEARCH_PRICE,
                        Blueprint.COLUMN_NAME_RESEARCH_COPY_TIME },
                null, null, null);
    }

    @Override
    public void onLoadFinished(Cursor data) {
        if (DbUtil.hasAtLeastOneRow(data)) {

            parentTypeId = data.getInt(data.getColumnIndexOrThrow(Blueprint.COLUMN_NAME_PARENT_TYPE_ID));
            int maxProdLimit = data.getInt(data.getColumnIndexOrThrow(Blueprint.COLUMN_NAME_MAX_PRODUCTION_LIMIT));
            metaLevel = data.getShort(data.getColumnIndexOrThrow(Blueprint.COLUMN_NAME_INVENTION_ITEM_META_LEVEL));
            decryptorId = data.getInt(data.getColumnIndexOrThrow(Blueprint.COLUMN_NAME_DECRYPTOR_ID));
            double cost = data.getDouble(data.getColumnIndexOrThrow(Blueprint.COLUMN_NAME_RESEARCH_PRICE));

            if (decryptorId != 0) {
                currentDecryptorBonuses = DecryptorUtil.getDecryptorBonusesOrDefault(decryptorId);
            }

            requiredSkillInventionFragment.setParentFragment(this);
            requiredSkillInventionFragment.setParentTypeId(parentTypeId);

            requiredItemsInventionFragment.setParentFragment(this);
            requiredItemsInventionFragment.setDecryptorId(decryptorId);
            requiredItemsInventionFragment.setParentTypeId(parentTypeId);
            requiredItemsInventionFragment.setMaxProdLimit(maxProdLimit);

            requiredDecryptorFragment.setParentFragment(this);
            requiredDecryptorFragment.setBlueprintId(blueprintId);
            requiredDecryptorFragment.setProducedItemId(producedItemId);

            int metaGroupId = getArguments().getInt("metaGroupId", -1);
            Bundle blueprintBundle = BlueprintUtil.getBlueprintBundle(data, metaGroupId, true, false);

            int numberOfRuns = blueprintBundle.getInt("numberOfRuns", 0);
            int unitPerBatch = blueprintBundle.getInt("unitPerBatch", 0);
            double sellPrice = getArguments().getDouble("sellPrice", 0);
            producePrice = getArguments().getDouble("producePrice", 0);
            double profitOnSingleItem = sellPrice - producePrice;
            double blueprintProfit = profitOnSingleItem * unitPerBatch * numberOfRuns;

            if (!data.isNull(data.getColumnIndexOrThrow(Blueprint.COLUMN_NAME_RESEARCH_PRICE))) {
                BlueprintUtil.setBlueprintCost(costTextView, cost, getResources());
                profitTextView.setText(PricesUtils.formatPrice(blueprintProfit, getActivity(), true));
            } else {
                costTextView.setVisibility(View.GONE);
                profitTextView.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
    }

    @Override
    public void onResume() {
        super.onResume();
        initOrRestart();
        requiredSkillInventionFragment.initOrRestart();
        requiredItemsInventionFragment.initOrRestart();

        getActivity().registerReceiver(receiver, new IntentFilter(PriceUpdaterService.PRICE_CHANGED_ACTION));
    }

    @Override
    public void onPause() {
        super.onPause();

        getActivity().unregisterReceiver(receiver);
    }

    /**
     * @param encryptionSkillId the encryptionSkillId to set
     */
    public void setEncryptionSkillId(int encryptionSkillId) {
        requiredDecryptorFragment.setDecryptorId(decryptorId);
        requiredDecryptorFragment.setEncryptionSkillId(encryptionSkillId);
    }

    /**
     * @param singleBlueprintCopyPrice the singleBlueprintCopyPrice to set
     */
    public void setSingleBlueprintCopyPrice(double singleBlueprintCopyPrice) {
        this.singleBlueprintCopyPrice = singleBlueprintCopyPrice;
    }

    /**
     * @param requiredItemsBlueprintCopyPrice the requiredItemsBlueprintCopyPrice to set
     */
    public void setRequiredItemsBlueprintCopyPrice(double requiredItemsBlueprintCopyPrice) {
        this.singleBlueprintCopyPrice += requiredItemsBlueprintCopyPrice;
    }

    /**
     * @param requiredItemsPrice the requiredItemsPrice to set
     */
    public void setRequiredItemsPrice(double requiredItemsPrice) {
        double blueprintCost = singleBlueprintCopyPrice * numberOfChances + requiredItemsPrice;

        TextView costTV = (TextView) getActivity().findViewById(R.id.COST_VALUE);
        BlueprintUtil.setBlueprintCost(costTV, blueprintCost, getResources());

        if (blueprintCost != blueprintTotalCost) {
            new UpdateBlueprintPriceTask().execute(blueprintCost);
            blueprintTotalCost = blueprintCost;
        }
    }

    /**
     * @param decryptorId the decryptorId to set
     */
    public void setDecryptorId(int decryptorId) {
        if (this.decryptorId != decryptorId) {
            this.decryptorId = decryptorId;

            if (decryptorId != 0) {
                currentDecryptorBonuses = DecryptorUtil.getDecryptorBonusesOrDefault(decryptorId);
            }

            updateInventionChances();
        }
    }

    void updateInventionChances(short encryptionSkillLevel, short datacore1SkillLevel, short datacore2SkillLevel) {
        if (this.encryptionSkillLevel != encryptionSkillLevel || this.datacore1SkillLevel != datacore1SkillLevel
                || this.datacore2SkillLevel != datacore2SkillLevel) {
            this.encryptionSkillLevel = encryptionSkillLevel;
            this.datacore1SkillLevel = datacore1SkillLevel;
            this.datacore2SkillLevel = datacore2SkillLevel;

            updateInventionChances();
        }
    }

    private void updateInventionChances() {
        inventionChances = FormulaCalculator.calculateInventionChances(
                FormulaCalculator.getBaseInventionChances(producedItemId, producedItemGroupId),
                encryptionSkillLevel, datacore1SkillLevel, datacore2SkillLevel, metaLevel,
                currentDecryptorBonuses.probabilityMultiplier);

        numberOfChances = (int) FloatMath.ceil(1 / (inventionChances));

        inventionChancesTextView.setText(nfPercent.format(inventionChances));
        requiredItemsInventionFragment.setParentFragment(this);
        requiredItemsInventionFragment.setDecryptorId(decryptorId);
        requiredItemsInventionFragment.setNumberOfChances(numberOfChances);
    }

    private class UpdateBlueprintPriceTask extends AsyncTask<Double, Void, Void> {

        @Override
        protected Void doInBackground(Double... params) {
            double price = params[0];

            Uri updateBlueprintUri = ContentUris.withAppendedId(Blueprint.CONTENT_ID_URI_BASE, blueprintId);
            ContentValues values = new ContentValues();
            values.put(Blueprint.COLUMN_NAME_RESEARCH_PRICE, price);

            if (getActivity() != null && getActivity().getContentResolver() != null) {
                getActivity().getContentResolver().update(updateBlueprintUri, values, null, null);
            }
            return null;
        }
    }

    private class PriceChangedBroadCastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            double price = intent.getDoubleExtra(Prices.COLUMN_NAME_PRODUCE_PRICE, 0);
            producePrice = price;
        }
    }
}