package com.example.android.basicsyncadapter.quotesFragments;
import android.annotation.TargetApi;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.content.SharedPreferences;
import android.content.SyncResult;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.telephony.PhoneNumberUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import com.example.android.basicsyncadapter.QuoteDetailsActivity;
import com.example.android.basicsyncadapter.R;
import com.example.android.basicsyncadapter.model.Quote;
import com.example.android.basicsyncadapter.model.User;
import com.example.android.basicsyncadapter.net.FeedParser;
import com.example.android.basicsyncadapter.provider.MaterialsContract;
import com.example.android.basicsyncadapter.provider.QuoteMaterialsContract;
import com.example.android.basicsyncadapter.provider.UserContract;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import static com.example.android.basicsyncadapter.quotesRecycler.QuoteListAdapter.getCurrentLocale;
public class QuoteViewFragment extends Fragment {
private NumberFormat defaultFormat;
private static final String quoteMaterialsTableName = "match_quote_product";
/**
* Project used when querying content provider. Returns all known fields.
*/
private static final String[] QUOTE_MATERIALS_PROJECTION = new String[] {
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry._ID,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_ENTRY_ID,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_QUOTE_ID,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_PRODUCT_ID,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_WIDTH,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_LENGTH,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_HEIGHT,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_LOCATION,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_QUANTITY,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_LOCKING_HANDLE_SIDE,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_POWER,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_INSULATED,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_CUSTOMER_SUPPLIED,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_STOREY,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_WINDOW_INSERTS,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_BOARD_FEET,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_PRICE_PER_K,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_UNIT_PRICE,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_COMMISSION_SPIFF,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_MARKUP_SPIFF,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_TOTAL_COMMISSION_SPIFF,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_TOTAL_MARKUP_SPIFF,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_TOTAL_PRICE_CALCULATION_ID,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_PURCHASE_ORDER_ID,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_COLOUR_TYPE_ID,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_GROUP_PRICES,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_TOTAL_PRICE,
quoteMaterialsTableName + "." + QuoteMaterialsContract.Entry.COLUMN_NAME_UNIT_OF_MEASURE
};
String customerNameText;
TextView customerName;
TextView quoteNumber;
TextView quoteDate;
TextView quoteExpiry;
TextView quotePrice;
TextView quotePrice2;
TextView buildingDetails;
TextView buildingClassification;
TextView trussDescription;
TextView strappingDescription;
TextView metalDescription;
TextView ridgeDescription;
TextView stormBracketDescription;
TextView blueprintsDescription;
TextView wallDescription;
TextView ceilingInsulationDescription;
TextView insulationSectionHeader;
TextView upgradePrice3PlyPerma;
TextView upgradePrice4PlyPerma;
TextView upgradePrice8400Perma;
LinearLayout quoteInsulationSection;
LinearLayout quoteInsulationSubsection;
LinearLayout warrantySection;
TableLayout optionsTable;
TableLayout upgradesTable;
TableRow upgradeRow3PlyPerma;
TableRow upgradeRow4PlyPerma;
TableRow upgradeRow8400Perma;
Quote quote;
Long startTime;
public QuoteViewFragment() {
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
Intent intent = getActivity().getIntent();
quote = (Quote) intent.getSerializableExtra("quote");
LoadQuoteValuesAsynchronously quoteValueLoader = new LoadQuoteValuesAsynchronously(this, getContext().getContentResolver(), quote, startTime);
quoteValueLoader.execute();
}
public void loadQuoteValues()
{
Double quotePriceValue = quote.calculateQuotePrice();
// remove all views before populating the view again
optionsTable.removeAllViews();
buildingDetails.setText(String.valueOf(quote.getBuildingWidth()) + "' X " + String.valueOf(quote.getBuildingLength() + "' X " + String.valueOf(quote.getBuildingHeight() + "' " + quote.getBuildingType())));
quotePrice.setText(String.valueOf(defaultFormat.format(quotePriceValue)));
quotePrice2.setText(String.valueOf(defaultFormat.format(quotePriceValue)));
buildingClassification.setText("• " + quote.getOccupancy() + " Occupancy Classification");
trussDescription.setText("• " + quote.getEvePostSpacing() + "' O/C Engineered Trusses" + (quote.getDoublePlyRafters() ? ", Double Ply" : ""));
metalDescription.setText("• Premium 29 gauge Hi-Tensile FC36 profile metal including a 3/4\" rib");
ridgeDescription.setText("• " + quote.getRidge());
quoteNumber.setText("Quote: " + quote.getNumber());
quoteExpiry.setText(formatDate(quote.getQuotedDate(), 14));
if (quote.getStormBrackets())
stormBracketDescription.setText("• Storm Brackets");
if (quote.getBlueprints())
blueprintsDescription.setVisibility(View.VISIBLE);
else
blueprintsDescription.setVisibility(View.GONE);
wallDescription.setText("• " + quote.getEvePostSpacing() + "' O/C " + quote.getWallType().replace("'", "'").replace(""", "\"") + (quote.getPostDiscs() ? " with Post Disc" : ""));
ceilingInsulationDescription.setText("• R40 Ceiling Insulation");
if (quote.getInsulated()) {
quoteInsulationSection.setVisibility(View.VISIBLE);
quoteInsulationSubsection.setVisibility(View.VISIBLE);
insulationSectionHeader.setText("Insulation Package: " + quote.getInsulationWidth() + "' X " + quote.getInsulationLength() + "'");
}
if (quote.getWarranty5())
warrantySection.setVisibility(View.VISIBLE);
// get currency locale for proper formatting
NumberFormat defaultFormat = NumberFormat.getCurrencyInstance(getCurrentLocale(getContext()));
quoteDate.setText(formatDate(quote.getQuotedDate(), 0));
// if any upgrade options were selected, show the table
if (
quote.get3PlyPermaPostUpgrade()
|| quote.get4PlyPermaPostUpgrade()
|| quote.get8400PermaPostUpgrade()
)
upgradesTable.setVisibility(View.VISIBLE);
if (quote.get3PlyPermaPostUpgrade()) {
upgradePrice3PlyPerma.setText("$ ");
upgradeRow3PlyPerma.setVisibility(View.VISIBLE);
}
if (quote.get4PlyPermaPostUpgrade()) {
upgradePrice4PlyPerma.setText("$ ");
upgradeRow4PlyPerma.setVisibility(View.VISIBLE);
}
if (quote.get8400PermaPostUpgrade()) {
upgradePrice8400Perma.setText("$ ");
upgradeRow8400Perma.setVisibility(View.VISIBLE);
}
try {
// json string coming in is contained inside square brackets
// assigning to a JSONArray and then JSONObject removes these brackets
JSONArray overheadList = new JSONArray(quote.getOverheadDoors());
JSONArray slidingList = new JSONArray(quote.getSlidingDoors());
JSONArray foldingList = new JSONArray(quote.getFoldingDoors());
JSONArray manDoorList = new JSONArray(quote.getManDoors());
JSONArray windowList = new JSONArray(quote.getWindows());
JSONArray customWindowList = new JSONArray(quote.getCustomWindows());
JSONArray wallLightList = new JSONArray(quote.getWallLights());
JSONArray kickWallList = new JSONArray(quote.getKickWall());
JSONArray partitionWallList = new JSONArray(quote.getPartitionWalls());
JSONArray mezzanineList = new JSONArray(quote.getMezzanines());
JSONArray leanToList = new JSONArray(quote.getLeanTos());
JSONArray customsList = new JSONArray(quote.getCustoms());
// add overhead doors to the quote options list
for (int i = 0; i < overheadList.length(); i++) {
// get each overhead door
JSONObject jsonDoors = (JSONObject)overheadList.get(i);
System.out.println("asdf door operator: " + jsonDoors.getString("operator"));
String overheadWindowQuantity = jsonDoors.get("window_inserts").toString();
String overheadDescription =
jsonDoors.getString("customer_supplied").equals("true") ?
"Prepared " + jsonDoors.getString("location") + " " + jsonDoors.getString("width") + "' x " + jsonDoors.getString("height") + "' Opening"
: jsonDoors.getString("width") + "' X " + jsonDoors.getString("height") + "' Overhead Door";
createQuoteOptionRow(
jsonDoors.getString("quantity"),
overheadDescription +
(jsonDoors.getString("customer_supplied").equals("true") ? "" : ", " + jsonDoors.getString("location")) +
(jsonDoors.getString("operator").equals("None") ? "" : ", " + jsonDoors.getString("operator")) + // use getString because it's pulling from the model, not the input
(jsonDoors.getString("bow_strap").equals("true") ? ", Bow Strap" : "") +
(overheadWindowQuantity.equals("") ? "" : ", " + overheadWindowQuantity + " Window Insert" + (Integer.parseInt(overheadWindowQuantity) > 1 ? "s" : "") + " Per Door"),
quote,
optionsTable
);
}
// add sliding doors to the quote options list
for (int i = 0; i < slidingList.length(); i++) {
// get each sliding door
JSONObject jsonDoors = (JSONObject)slidingList.get(i);
createQuoteOptionRow(jsonDoors.getString(
"quantity"),
jsonDoors.getString("width") +
"' X " + jsonDoors.getString("height") +
", " +
"Sliding Door" +
"' " +
jsonDoors.getString("location"),
quote,
optionsTable
);
}
// add folding doors to the quote options list
for (int i = 0; i < foldingList.length(); i++) {
// get each folding door
JSONObject jsonDoors = (JSONObject)foldingList.get(i);
createQuoteOptionRow(
jsonDoors.getString("quantity"),
jsonDoors.getString("width") +
"' X " +
jsonDoors.getString("height") +
"' " +
"Bi-Fold Door" +
(jsonDoors.getString("lock").equals("None") ? "" :
jsonDoors.getString("lock").equals("Left") || jsonDoors.getString("lock").equals("Right") ?
", " + jsonDoors.getString("lock") + " Side Handle" :
", " + jsonDoors.getString("lock") + " With Remote") +
", " +
jsonDoors.getString("insulated") +
" Insulation, " +
jsonDoors.getString("windows") +
" Windows Per Door" +
(jsonDoors.getBoolean("column_supports") ? ", Column Supports": "") +
(jsonDoors.getBoolean("jtrack") ? ", J Track": "") +
", With Double Truss" +
(jsonDoors.getBoolean("shear-wall") ? ", With Shear Wall Package" : ""),
quote,
optionsTable
);
}
// add gable vents to the quote options list
if (quote.getGableVents() > 0)
createQuoteOptionRow(
String.valueOf(quote.getGableVents()),
"Gable Vents",
quote,
optionsTable
);
// add x-tension straps to the quote options list
if (quote.getXTensionStrapQuantity() > 0)
createQuoteOptionRow(
String.valueOf(quote.getXTensionStrapQuantity()),
"X-Tension Straps",
quote,
optionsTable
);
// add storm brackets to the quote options list
if (quote.getStormBracketQuantity() > 0)
createQuoteOptionRow(
String.valueOf(quote.getStormBracketQuantity()),
"Storm Brackets",
quote,
optionsTable
);
// add man doors to the quote options list
for (int i = 0; i < manDoorList.length(); i++) {
// get each
JSONObject itemList = (JSONObject)manDoorList.get(i);
createQuoteOptionRow(
itemList.getString("quantity"),
getNameFromMaterialId(itemList.getInt("type")) +
(itemList.getInt("storey") == 1 ? ", 2nd Storey" : ""),
quote,
optionsTable
);
}
// add windows to the quote options list
for (int i = 0; i < windowList.length(); i++) {
// get each
JSONObject itemList = (JSONObject)windowList.get(i);
createQuoteOptionRow(
itemList.getString("quantity"),
getNameFromMaterialId(itemList.getInt("type")) +
(itemList.getInt("storey") == 1 ? ", 2nd Storey" : ""),
quote,
optionsTable
);
}
// add custom windows to the quote options list
for (int i = 0; i < customWindowList.length(); i++) {
// get each
JSONObject itemList = (JSONObject)customWindowList.get(i);
createQuoteOptionRow(
itemList.getString("quantity"),
itemList.getString("width") +
"'x" +
itemList.getString("height") +
"' " +
itemList.getString("type") +
" " +
itemList.getString("pane") +
" Custom Window",
quote,
optionsTable
);
}
// add wall light to the quote options list
for (int i = 0; i < wallLightList.length(); i++) {
// get each
JSONObject itemList = (JSONObject)wallLightList.get(i);
createQuoteOptionRow(
itemList.getString("quantity"),
itemList.getInt("length") +
"' of " +
itemList.getInt("height") +
"' High " +
itemList.getString("location") +
" Wall Light",
quote,
optionsTable
);
}
// add gable vents to the quote options list
if (quote.getGableVents() > 0)
createQuoteOptionRow(
String.valueOf(quote.getGableVents()),
"Gable Vents",
quote,
optionsTable
);
// add kick wall to the quote options list
for (int i = 0; i < kickWallList.length(); i++) {
// get each
JSONObject itemList = (JSONObject)kickWallList.get(i);
createQuoteOptionRow(
"1", // always 1
itemList.getInt("length") +
"' of " +
itemList.getInt("height") +
"' High " +
itemList.getString("location") +
" Kick Wall",
quote,
optionsTable
);
}
// add eve soffit to the quote options list
if (quote.getEveSoffitLength() > 0)
createQuoteOptionRow(
"1",
quote.getEveSoffitLength() +
"' of Eve Soffit",
quote,
optionsTable
);
// add gable soffit to the quote options list
if (quote.getGableSoffitLength() > 0)
createQuoteOptionRow(
"1",
quote.getGableSoffitLength() +
"' of Gable Soffit",
quote,
optionsTable
);
// add smoke stop to the quote options list
if (quote.getSmokeStops() > 0)
createQuoteOptionRow(
String.valueOf(quote.getSmokeStops()),
"Smoke Stop",
quote,
optionsTable
);
// add gable stop to the quote options list
if (quote.getGableStops() > 0)
createQuoteOptionRow(
String.valueOf(quote.getGableStops()),
"Gable Stop",
quote,
optionsTable
);
// add fire stop to the quote options list
if (quote.getFireStops() > 0)
createQuoteOptionRow(
String.valueOf(quote.getFireStops()),
"Fire Stop",
quote,
optionsTable
);
// this might not be set yet
// if (quote.getMaterials() != null) {
int smokeDamperQuantity = quote.getQuantifyOfQuoteProduct(quote.SMOKE_DAMPERS);
// int smokeDamperQuantity = getItemQuantity(quote.SMOKE_DAMPERS, quote.getQuoteId());
if (smokeDamperQuantity > 0)
createQuoteOptionRow(String.valueOf(smokeDamperQuantity), "Smoke Damper" + (smokeDamperQuantity > 1 ? "s" : ""), quote, optionsTable);
// }
// add drift load rafters to the quote options list
if (quote.getDriftLoadRafters() > 0)
createQuoteOptionRow(
String.valueOf(quote.getDriftLoadRafters()),
"Drift Load Rafters",
quote,
optionsTable
);
// add attic hatches to the quote options list
if ((quote.getAtticHatches() + quote.getAdditionalAtticHatches()) > 0)
createQuoteOptionRow(
String.valueOf((quote.getAtticHatches() + quote.getAdditionalAtticHatches())),
"Attic Hatches",
quote,
optionsTable
);
// add mezzanine to the quote options list
for (int i = 0; i < mezzanineList.length(); i++) {
// get each
JSONObject itemList = (JSONObject)mezzanineList.get(i);
createQuoteOptionRow(
"1", // always 1
itemList.getInt("width") +
"' x " +
itemList.getInt("width") +
"' Mezzanine",
quote,
optionsTable
);
}
// add stairs to the quote options list
if (quote.getStairsNoTurns() > 0)
createQuoteOptionRow(
String.valueOf(quote.getStairsNoTurns()),
"Stairs (No Turns)",
quote,
optionsTable
);
// add stairs to the quote options list
if (quote.getStairsOneTurn() > 0)
createQuoteOptionRow(
String.valueOf(quote.getStairsOneTurn()),
"Stairs (One Turn)",
quote,
optionsTable
);
// add stairs to the quote options list
if (quote.getStairsTwoTurns() > 0)
createQuoteOptionRow(
String.valueOf(quote.getStairsTwoTurns()),
"Stairs (Two Turns)",
quote,
optionsTable
);
// add customs to the quote options list
for (int i = 0; i < customsList.length(); i++) {
// get each
JSONObject itemList = (JSONObject)customsList.get(i);
createQuoteOptionRow(
"",
itemList.getString("details"),
quote,
optionsTable
);
}
} catch (JSONException e) {
System.out.println("asdf JSON no go go: " + e);
e.printStackTrace();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
defaultFormat = NumberFormat.getCurrencyInstance(getCurrentLocale(getActivity().getApplicationContext()));
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_quote_view, container, false);
String inputsTag = getTag();
((QuoteDetailsActivity)getActivity()).setQuoteInputs(inputsTag);
// Intent intent = getActivity().getIntent();
// quote = (Quote) intent.getSerializableExtra("quote");
String customerCompanyDescription = "";
TextView salesmanName = (TextView)v.findViewById(R.id.salesman_name);
TextView salesmanPhone = (TextView)v.findViewById(R.id.salesman_phone);
TextView salesmanEmail = (TextView)v.findViewById(R.id.salesman_email);
customerName = (TextView)v.findViewById(R.id.customer_name);
TextView customerPhone = (TextView)v.findViewById(R.id.customer_phone);
TextView customerEmail = (TextView)v.findViewById(R.id.customer_email);
TextView customerCity = (TextView)v.findViewById(R.id.customer_city);
TextView customerProvince = (TextView)v.findViewById(R.id.customer_province);
TextView customerPostalCode = (TextView)v.findViewById(R.id.customer_postal_Code);
TextView customerExtraReference = (TextView)v.findViewById(R.id.customer_extra_reference);
quoteNumber = (TextView)v.findViewById(R.id.quote_number);
quoteDate = (TextView)v.findViewById(R.id.quote_date);
quoteExpiry = (TextView)v.findViewById(R.id.quote_expiry);
quotePrice = (TextView)v.findViewById(R.id.quote_price);
buildingDetails = (TextView)v.findViewById(R.id.building_details);
buildingClassification = (TextView)v.findViewById(R.id.quote_classification);
trussDescription = (TextView)v.findViewById(R.id.quote_truss_description);
strappingDescription = (TextView)v.findViewById(R.id.quote_strapping_description);
metalDescription = (TextView)v.findViewById(R.id.quote_metal_description);
ridgeDescription = (TextView)v.findViewById(R.id.quote_ridge_description);
stormBracketDescription = (TextView)v.findViewById(R.id.quote_storm_bracket_description);
blueprintsDescription = (TextView)v.findViewById(R.id.quote_blueprints_description);
wallDescription = (TextView)v.findViewById(R.id.wall_description);
ceilingInsulationDescription = (TextView)v.findViewById(R.id.ceiling_insulation_description);
insulationSectionHeader = (TextView)v.findViewById(R.id.quote_insulation_section_header);
quotePrice2 = (TextView)v.findViewById(R.id.quote_price_subsection);
upgradePrice3PlyPerma = (TextView)v.findViewById(R.id.upgrade_price_3PlyPerma);
upgradePrice4PlyPerma = (TextView)v.findViewById(R.id.upgrade_price_4PlyPerma);
upgradePrice8400Perma = (TextView)v.findViewById(R.id.upgrade_price_8400Perma);
quoteInsulationSection = (LinearLayout)v.findViewById(R.id.quote_insulation_section);
quoteInsulationSubsection = (LinearLayout)v.findViewById(R.id.quote_insulation_subsection);
warrantySection = (LinearLayout)v.findViewById(R.id.quote_warranty_subsection);
optionsTable = v.findViewById(R.id.options_table);
upgradesTable = v.findViewById(R.id.upgrades_table);
upgradeRow3PlyPerma = (TableRow)v.findViewById(R.id.upgrade_row_3PlyPerma);
upgradeRow4PlyPerma = (TableRow)v.findViewById(R.id.upgrade_row_4PlyPerma);
upgradeRow8400Perma = (TableRow)v.findViewById(R.id.upgrade_row_8400Perma);
salesmanName.setText(quote.getAssignedName());
// salesmanPhone.setText(user.getPhone());
// salesmanEmail.setText(user.getEmail());
if (!quote.getCustomerCompany().equals(""))
customerCompanyDescription = quote.getCustomerCompany() + " care of ";
customerName.setText(quote.getCustomerFirstName() + " " + quote.getCustomerLastName());
customerPhone.setText(PhoneNumberUtils.formatNumber(quote.getCustomerPhone()));
customerEmail.setText(quote.getCustomerEmail());
customerCity.setText(quote.getCustomerCity());
// customerProvince.setText(quote.getCustomerProvinceId());
customerPostalCode.setText(quote.getCustomerPostalCode());
customerExtraReference.setText(quote.getCustomerExtraReference());
// LoadQuoteValuesAsynchronously quoteValueLoader = new LoadQuoteValuesAsynchronously(this, getContext().getContentResolver(), quote);
// quoteValueLoader.execute();
// loadQuoteValues();
return v;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.menu_chat_fragment, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@TargetApi(Build.VERSION_CODES.N)
public static Locale getCurrentLocale(Context c) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
return c.getResources().getConfiguration().getLocales().get(0);
} else {
//noinspection deprecation
return c.getResources().getConfiguration().locale;
}
}
public String formatDate(String date, int addDays)
{
String dateString = "";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", getCurrentLocale(getActivity().getApplicationContext()));
SimpleDateFormat outputFormat = new SimpleDateFormat("MMM d, yyyy", getCurrentLocale(getActivity().getApplicationContext()));
try {
Date newDate = format.parse(date);
if (addDays > 0)
{
Calendar c = Calendar.getInstance();
c.setTime(newDate);
c.add(Calendar.DATE, addDays);
newDate = c.getTime();
}
dateString = outputFormat.format(newDate);
} catch (ParseException e) {
System.out.println("asdf error: " + e);
e.printStackTrace();
}
return dateString;
}
public void createQuoteOptionRow(String itemQuantity, String itemDescription, Quote quote, TableLayout optionsTable)
{
TableRow tr = new TableRow(getActivity());
TextView itemQuantityTextView = new TextView(getActivity());
TextView itemDescriptionTextView = new TextView(getActivity());
TableRow.LayoutParams tableLayoutParamsQuantity = new TableRow.LayoutParams(
0,
TableRow.LayoutParams.WRAP_CONTENT);
tableLayoutParamsQuantity.weight = (float) 0.23;
TableRow.LayoutParams tableLayoutParamsDescription = new TableRow.LayoutParams(
0,
TableRow.LayoutParams.WRAP_CONTENT);
tableLayoutParamsDescription.weight = (float) 0.77;
TableLayout.LayoutParams tableLayoutParamsRow = new TableLayout.LayoutParams(
TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT);
// set the text for each textview
itemQuantityTextView.setText(itemQuantity);
itemDescriptionTextView.setText(itemDescription);
// set the background in order to get a table border
itemQuantityTextView.setBackgroundResource(R.drawable.quote_options_border);
itemDescriptionTextView.setBackgroundResource(R.drawable.quote_options_border);
// this gravity and one above are needed to center the text
itemQuantityTextView.setPadding(10, 10, 10, 10);
itemQuantityTextView.setGravity(Gravity.CENTER);
itemDescriptionTextView.setPadding(10, 10, 10, 10);
// apply the layout parameters to the textviews
itemQuantityTextView.setLayoutParams(tableLayoutParamsQuantity);
itemDescriptionTextView.setLayoutParams(tableLayoutParamsDescription);
tr.setLayoutParams(tableLayoutParamsRow);
// add the views to the row and the row to the table
tr.addView(itemQuantityTextView);
tr.addView(itemDescriptionTextView);
optionsTable.addView(tr);
}
public String getNameFromMaterialId(int itemId)
{
String returnValue = "";
final ContentResolver contentResolver = getContext().getContentResolver();
Uri uri = MaterialsContract.Entry.CONTENT_URI; // Get all entries
Cursor materialsCursor = contentResolver.query(uri, new String[] {"item_name"}, " entry_id = ?", new String[] { String.valueOf(itemId) }, null);
assert materialsCursor != null;
if (materialsCursor.getCount() > 0) {
materialsCursor.moveToFirst();
returnValue = materialsCursor.getString(0).replaceAll("'", "'").replaceAll("'", "'");
}
return returnValue;
}
private int getItemQuantity(int itemId, int quoteId)
{
int returnValue = 0;
final ContentResolver contentResolver = getContext().getContentResolver();
Uri uri = QuoteMaterialsContract.Entry.CONTENT_URI; // Get all entries
Cursor materialsCursor = contentResolver.query(uri, new String[] {"quantity"}, " product_id = ? and quote_id = ?", new String[] { String.valueOf(itemId), String.valueOf(quoteId) }, null);
assert materialsCursor != null;
if (materialsCursor.getCount() > 0) {
materialsCursor.moveToFirst();
String quantitiesString = materialsCursor.getString(0);
// remove the extra array characters
quantitiesString = quantitiesString
.replace("[", "")
.replace("]", "")
.replace("\"", "");
// create an array list from the comman delimited string of quantities
List<String> quantitiesList = new ArrayList<String>(Arrays.asList(quantitiesString.split(",")));
// loop through array and add up all the quantities
for (int i = 0; i < quantitiesList.size(); i++)
returnValue =+ Integer.parseInt(quantitiesList.get(i));
}
return returnValue;
}
}
class LoadQuoteValuesAsynchronously extends AsyncTask<String, Void, String> {
ContentResolver contentResolver;
Quote quote;
private QuoteViewFragment quoteViewFragment;
Long startTime;
public LoadQuoteValuesAsynchronously(QuoteViewFragment quoteViewFragment, ContentResolver contentResolver, Quote quote, Long startTime) {
this.quoteViewFragment = quoteViewFragment;
this.contentResolver = contentResolver;
this.quote = quote;
this.startTime = startTime;
// System.out.println("asdf six: " + (System.currentTimeMillis() - startTime));
}
protected String doInBackground(String... params) {
int count = 0;
// System.out.println("asdf seven: " + (System.currentTimeMillis() - startTime));
// make a manual database call to get the name of the selected post type
Uri uri = QuoteMaterialsContract.Entry.CONTENT_URI; // Get all entries
// System.out.println("asdf quote to retrieve materials is " + quote.getQuoteId());
Cursor quoteMaterialsCursor = contentResolver.query(uri, QuoteMaterialsContract.Entry.PROJECTION, " quote_id = ?", new String[] { String.valueOf(quote.getQuoteId()) }, " product_id asc");
assert quoteMaterialsCursor != null;
// System.out.println("asdf materials cursor size: " + quoteMaterialsCursor.getCount());
Map<String, String> materialsHashmap = new HashMap<String, String>();
// System.out.println("asdf eight: " + (System.currentTimeMillis() - startTime));
while (quoteMaterialsCursor.moveToNext()) {
// if (count % 50 == 0)
// System.out.println("asdf nine: " + (System.currentTimeMillis() - startTime));
Map<String, String> columns = new HashMap<String, String>();
// create a hashmap from each row
for (int i = 0; i < quoteMaterialsCursor.getColumnCount(); i++)
columns.put(quoteMaterialsCursor.getColumnName(i), quoteMaterialsCursor.getString(i));
// if (count % 50 == 0)
// System.out.println("asdf ten: " + (System.currentTimeMillis() - startTime));
JSONObject jsonColumns = new JSONObject(columns);
try {
materialsHashmap.put(jsonColumns.getString("product_id"), jsonColumns.toString());
} catch (JSONException e) {
System.out.println("asdf error: " + e);
e.printStackTrace();
}
count++;
}
// System.out.println("asdf eleven: " + (System.currentTimeMillis() - startTime));
quoteMaterialsCursor.close();
JSONObject jsonMaterials = new JSONObject(materialsHashmap);
// System.out.println("asdf set materials to " + jsonMaterials.toString());
quote.setMaterials(jsonMaterials.toString());
// System.out.println("asdf twelve: " + (System.currentTimeMillis() - startTime));
return "";
}
@Override
protected void onPostExecute(String s){
// load all values into quote
// System.out.println("asdf 98: " + (System.currentTimeMillis() - startTime));
quoteViewFragment.loadQuoteValues();
// System.out.println("asdf 99: " + (System.currentTimeMillis() - startTime));
}
}