/**
   * Called when "delete" button is clicked.
   *
   * @param v
   */
  public void onDeleteClick(View v) {
    String objectType =
        ((EditText) findViewById(R.id.delete_object_type_text)).getText().toString();
    String objectId = ((EditText) findViewById(R.id.delete_object_id_text)).getText().toString();

    sendRequest(RestRequest.getRequestForDelete(apiVersion, objectType, objectId));
  }
 /**
  * Delete records specified in idToNames
  *
  * @param ids
  * @throws Exception
  */
 protected void deleteRecordsOnServer(Set<String> ids, String objectType) throws Exception {
   for (String id : ids) {
     RestRequest request =
         RestRequest.getRequestForDelete(
             ApiVersionStrings.getVersionNumber(targetContext), objectType, id);
     restClient.sendSync(request);
   }
 }
  /**
   * Called when "search" button is clicked.
   *
   * @param v
   */
  public void onSearchClick(View v) {
    String sosl = ((EditText) findViewById(R.id.search_sosl_text)).getText().toString();
    RestRequest request = null;
    try {
      request = RestRequest.getRequestForSearch(apiVersion, sosl);
    } catch (UnsupportedEncodingException e) {
      printHeader("Could not build search request");
      printException(e);
      return;
    }

    sendRequest(request);
  }
  /**
   * Called when "create" button is clicked.
   *
   * @param v
   */
  public void onCreateClick(View v) {
    String objectType =
        ((EditText) findViewById(R.id.create_object_type_text)).getText().toString();
    Map<String, Object> fields = parseFieldMap(R.id.create_fields_text);

    RestRequest request = null;
    try {
      request = RestRequest.getRequestForCreate(apiVersion, objectType, fields);
    } catch (Exception e) {
      printHeader("Could not build create request");
      printException(e);
      return;
    }
    sendRequest(request);
  }
  /**
   * Called when "retrieve" button is clicked.
   *
   * @param v
   */
  public void onRetrieveClick(View v) {
    String objectType =
        ((EditText) findViewById(R.id.retrieve_object_type_text)).getText().toString();
    String objectId = ((EditText) findViewById(R.id.retrieve_object_id_text)).getText().toString();
    List<String> fieldList = parseFieldList(R.id.retrieve_field_list_text);

    RestRequest request = null;
    try {
      request = RestRequest.getRequestForRetrieve(apiVersion, objectType, objectId, fieldList);
    } catch (Exception e) {
      printHeader("Could not build retrieve request");
      printException(e);
      return;
    }
    sendRequest(request);
  }
  /**
   * Sends a REST request.
   *
   * @param soql SOQL query.
   * @param obj Object being queried.
   */
  private void sendRequest(String soql, final String obj) throws UnsupportedEncodingException {
    final RestRequest restRequest =
        RestRequest.getRequestForQuery(getString(R.string.api_version), soql);
    client.sendAsync(
        restRequest,
        new AsyncRequestCallback() {

          @Override
          public void onSuccess(RestRequest request, RestResponse result) {
            try {
              final JSONArray records = result.asJSONObject().getJSONArray("records");
              if (obj.equals("Account")) {
                smartStoreIntf.insertAccounts(records);
              } else if (obj.equals("Opportunity")) {
                smartStoreIntf.insertOpportunities(records);
              } else {

                /*
                 * If the object is not an account or opportunity,
                 * we do nothing. This block can be used to save
                 * other types of records.
                 */
              }
            } catch (Exception e) {
              onError(e);
            } finally {
              progressDialog.dismiss();
              Toast.makeText(
                      MainActivity.this, "Records ready for offline access.", Toast.LENGTH_SHORT)
                  .show();
            }
          }

          @Override
          public void onError(Exception exception) {
            Toast.makeText(
                    MainActivity.this,
                    MainActivity.this.getString(
                        SalesforceSDKManagerWithSmartStore.getInstance()
                            .getSalesforceR()
                            .stringGenericError(),
                        exception.toString()),
                    Toast.LENGTH_LONG)
                .show();
          }
        });
  }
  private void getAccounts() {
    try {
      String accountId = getIntent().getStringExtra("ACCOUNT_ID");
      String soql = "select Id, Name from Contact where AccountId = '" + accountId + "'";
      RestRequest request = RestRequest.getRequestForQuery(apiVersion, soql);

      client.sendAsync(
          request,
          new AsyncRequestCallback() {

            public void onSuccess(RestResponse response) {
              try {
                if (response == null || response.asJSONObject() == null) return;

                JSONArray records = response.asJSONObject().getJSONArray("records");

                if (records.length() == 0) return;

                accounts = new String[records.length()];

                for (int i = 0; i < records.length(); i++) {
                  JSONObject album = (JSONObject) records.get(i);
                  accounts[i] = (i + 1) + ".  " + album.getString("Name");
                }
                ArrayAdapter<String> ad =
                    new ArrayAdapter<String>(
                        ContactListActivity.this, R.layout.list_item, accounts);
                lv.setAdapter(ad);
                EventsObservable.get().notifyEvent(EventType.RenditionComplete);
              } catch (Exception e) {
                e.printStackTrace();
                displayError(e.getMessage());
              }
            }

            public void onError(Exception exception) {
              displayError(exception.getMessage());
              EventsObservable.get().notifyEvent(EventType.RenditionComplete);
            }
          });

    } catch (Exception e) {
      e.printStackTrace();
      displayError(e.getMessage());
    }
  }
  @Override
  public JSONArray startFetch(SyncManager syncManager, long maxTimeStamp)
      throws IOException, JSONException {
    String queryToRun =
        maxTimeStamp > 0
            ? SoqlSyncDownTarget.addFilterForReSync(getQuery(), maxTimeStamp)
            : getQuery();
    syncManager
        .getRestClient()
        .sendSync(
            RestRequest.getRequestForResources(
                syncManager.apiVersion)); // cheap call to refresh session
    RestRequest request = buildQueryRequest(syncManager.getRestClient().getAuthToken(), queryToRun);
    RestResponse response = syncManager.sendSyncWithSmartSyncUserAgent(request);
    JSONArray records = parseSoapResponse(response);

    return records;
  }
  /**
   * Called when "upsert" button is clicked.
   *
   * @param v
   */
  public void onUpsertClick(View v) {
    String objectType =
        ((EditText) findViewById(R.id.upsert_object_type_text)).getText().toString();
    String externalIdField =
        ((EditText) findViewById(R.id.upsert_external_id_field_text)).getText().toString();
    String externalId =
        ((EditText) findViewById(R.id.upsert_external_id_text)).getText().toString();
    Map<String, Object> fields = parseFieldMap(R.id.upsert_fields_text);

    RestRequest request = null;
    try {
      request =
          RestRequest.getRequestForUpsert(
              apiVersion, objectType, externalIdField, externalId, fields);
    } catch (Exception e) {
      printHeader("Could not build upsert request");
      printException(e);
      return;
    }
    sendRequest(request);
  }
  /**
   * Helper methods to create "count" of test records
   *
   * @param count
   * @return map of id to name for the created accounts
   * @throws Exception
   */
  protected Map<String, String> createRecordsOnServer(int count, String objectType)
      throws Exception {
    Map<String, String> idToValues = new HashMap<String, String>();
    for (int i = 0; i < count; i++) {

      // Request.
      String fieldValue = createRecordName(objectType);
      Map<String, Object> fields = new HashMap<String, Object>();
      // add more object type if need to support to use this API
      // to create a new record on server
      switch (objectType) {
        case Constants.ACCOUNT:
          fields.put(Constants.NAME, fieldValue);
          break;
        case Constants.OPPORTUNITY:
          fields.put(Constants.NAME, fieldValue);
          fields.put("StageName", "Prospecting");
          DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
          fields.put("CloseDate", formatter.format(new Date()));
          break;
        default:
          break;
      }

      RestRequest request =
          RestRequest.getRequestForCreate(
              ApiVersionStrings.getVersionNumber(targetContext), objectType, fields);

      // Response.
      RestResponse response = restClient.sendSync(request);
      assertNotNull("Response should not be null", response);
      assertTrue("Response status should be success", response.isSuccess());
      String id = response.asJSONObject().getString(LID);
      idToValues.put(id, fieldValue);
    }
    return idToValues;
  }
 /**
  * Called when "get metadata" button is clicked.
  *
  * @param v
  */
 public void onGetMetadataClick(View v) {
   String objectType =
       ((EditText) findViewById(R.id.metadata_object_type_text)).getText().toString();
   sendRequest(RestRequest.getRequestForMetadata(apiVersion, objectType));
 }
  private void perFormFormFieldsRequest(String soql) {
    try {
      restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), soql);
      new ClientManager(
              getActivity(),
              SalesforceSDKManager.getInstance().getAccountType(),
              SalesforceSDKManager.getInstance().getLoginOptions(),
              SalesforceSDKManager.getInstance().shouldLogoutWhenTokenRevoked())
          .getRestClient(
              getActivity(),
              new ClientManager.RestClientCallback() {
                @Override
                public void authenticatedRestClient(RestClient client) {
                  if (client == null) {
                    SalesforceSDKManager.getInstance().logout(getActivity());
                    return;
                  } else {
                    Utilities.showloadingDialog(getActivity());
                    client.sendAsync(
                        restRequest,
                        new RestClient.AsyncRequestCallback() {

                          @Override
                          public void onSuccess(RestRequest request, RestResponse result) {
                            picklist = new ArrayList<FormField>();

                            Log.d("", result.toString());
                            NocMainFragment._webForm =
                                SFResponseManager.parseWebFormObject(result.toString());
                            for (int i = 0;
                                i < NocMainFragment._webForm.get_formFields().size();
                                i++) {
                              if (!NocMainFragment._webForm
                                      .get_formFields()
                                      .get(i)
                                      .getType()
                                      .equals("CUSTOMTEXT")
                                  && NocMainFragment._webForm.get_formFields().get(i).isParameter()
                                      == false
                                  && NocMainFragment._webForm.get_formFields().get(i).isQuery()
                                      == true) {
                                visaQueryBuilder +=
                                    NocMainFragment._webForm.get_formFields().get(i).getTextValue()
                                        + ",";
                              } else if (!NocMainFragment._webForm
                                      .get_formFields()
                                      .get(i)
                                      .isParameter()
                                  && NocMainFragment._webForm
                                      .get_formFields()
                                      .get(i)
                                      .getType()
                                      .equals("PICKLIST")) {
                                picklist.add(NocMainFragment._webForm.get_formFields().get(i));
                              }
                            }

                            visaQueryBuilder =
                                visaQueryBuilder.substring(0, visaQueryBuilder.length() - 1);
                            visaQuery =
                                String.format(
                                    visaQuery,
                                    visaQueryBuilder,
                                    NocActivity.get_visa().getVisa_Holder__r().getID());
                            PerformVisaQueryValues(NocMainFragment._webForm, visaQuery);
                          }

                          @Override
                          public void onError(Exception exception) {
                            Utilities.showToast(
                                getActivity(), RestMessages.getInstance().getErrorMessage());
                            Utilities.dismissLoadingDialog();
                            getActivity().finish();
                          }
                        });
                  }
                }
              });
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
  }
  private void PerformVisaQueryValues(final WebForm _webFormFields, String visaQuery) {
    try {
      restRequest = RestRequest.getRequestForQuery(getString(R.string.api_version), visaQuery);
      new ClientManager(
              getActivity(),
              SalesforceSDKManager.getInstance().getAccountType(),
              SalesforceSDKManager.getInstance().getLoginOptions(),
              SalesforceSDKManager.getInstance().shouldLogoutWhenTokenRevoked())
          .getRestClient(
              getActivity(),
              new ClientManager.RestClientCallback() {
                @Override
                public void authenticatedRestClient(RestClient client) {
                  if (client == null) {
                    SalesforceSDKManager.getInstance().logout(getActivity());
                    return;
                  } else {
                    client.sendAsync(
                        restRequest,
                        new RestClient.AsyncRequestCallback() {

                          @Override
                          public void onSuccess(RestRequest request, RestResponse result) {
                            _currentVisa =
                                SFResponseManager.parseVisaData(result.toString()).get(0);
                            visaJson = SFResponseManager.parseJsonVisaData(result.toString());
                            Utilities.dismissLoadingDialog();
                            formFields = _webFormFields.get_formFields();
                            new ClientManager(
                                    getActivity(),
                                    SalesforceSDKManager.getInstance().getAccountType(),
                                    SalesforceSDKManager.getInstance().getLoginOptions(),
                                    SalesforceSDKManager.getInstance()
                                        .shouldLogoutWhenTokenRevoked())
                                .getRestClient(
                                    getActivity(),
                                    new ClientManager.RestClientCallback() {
                                      @Override
                                      public void authenticatedRestClient(final RestClient client) {
                                        if (client == null) {
                                          System.exit(0);
                                        } else {

                                          new GetPickLists(client).execute(picklist);
                                        }
                                      }
                                    });
                            Log.d("Hello", result.toString());
                          }

                          @Override
                          public void onError(Exception exception) {
                            Utilities.showToast(
                                getActivity(), RestMessages.getInstance().getErrorMessage());
                            Utilities.dismissLoadingDialog();
                            getActivity().finish();
                          }
                        });
                  }
                }
              });
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
  }
  private void getCase() {

    // Creating Case and save id in the running Activity

    if (activity.geteServiceAdministration() != null) {
      activity.setCaseFields(new HashMap<String, Object>());
      Map<String, Object> caseFields = activity.getCaseFields();
      caseFields.put("Service_Requested__c", activity.geteServiceAdministration().getID());
      caseFields.put("AccountId", activity.getUser().get_contact().get_account().getID());
      caseFields.put("RecordTypeId", activity.getCaseRecordTypeId());
      caseFields.put("Status", "Draft");
      caseFields.put("Type", "License Services");
      caseFields.put("Origin", "Mobile");
      caseFields.put(
          "License_Ref__c",
          activity.getUser().get_contact().get_account().get_currentLicenseNumber().getId());
      caseFields.put("isCourierRequired__c", true);
      activity.setCaseFields(caseFields);
      if (activity.getInsertedCaseId() != null && !activity.getInsertedCaseId().equals("")) {
        try {
          restRequest =
              RestRequest.getRequestForUpdate(
                  getActivity().getString(R.string.api_version),
                  "Case",
                  activity.getInsertedCaseId(),
                  activity.getCaseFields());
        } catch (IOException e) {
          e.printStackTrace();
        }
      } else {
        try {
          restRequest =
              RestRequest.getRequestForCreate(
                  getActivity().getString(R.string.api_version), "Case", activity.getCaseFields());
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
      new ClientManager(
              getActivity(),
              SalesforceSDKManager.getInstance().getAccountType(),
              SalesforceSDKManager.getInstance().getLoginOptions(),
              SalesforceSDKManager.getInstance().shouldLogoutWhenTokenRevoked())
          .getRestClient(
              getActivity(),
              new ClientManager.RestClientCallback() {
                @Override
                public void authenticatedRestClient(final RestClient client) {
                  if (client == null) {
                    SalesforceSDKManager.getInstance().logout(getActivity());
                    return;
                  } else {
                    client.sendAsync(
                        restRequest,
                        new RestClient.AsyncRequestCallback() {
                          @Override
                          public void onSuccess(RestRequest request, RestResponse response) {
                            try {
                              JSONObject jsonObject = new JSONObject(response.toString());
                              activity.setInsertedCaseId(jsonObject.getString("id"));
                              // Getting other information Related to Created Case
                              try {
                                restRequest =
                                    RestRequest.getRequestForQuery(
                                        getString(R.string.api_version),
                                        SoqlStatements.getCaseNumberQuery(
                                            activity.getInsertedCaseId()));
                              } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                              }
                              client.sendAsync(
                                  restRequest,
                                  new RestClient.AsyncRequestCallback() {
                                    @Override
                                    public void onSuccess(
                                        RestRequest request, RestResponse response) {
                                      JSONObject jsonObject = null;
                                      Utilities.dismissLoadingDialog();
                                      try {
                                        jsonObject = new JSONObject(response.toString());
                                        JSONArray jsonArray =
                                            jsonObject.getJSONArray(JSONConstants.RECORDS);
                                        JSONObject jsonRecord = jsonArray.getJSONObject(0);
                                        Log.d("resultcase", response.toString());
                                        activity.setCaseNumber(jsonRecord.getString("CaseNumber"));
                                      } catch (JSONException e) {
                                        e.printStackTrace();
                                      }
                                    }

                                    @Override
                                    public void onError(Exception exception) {}
                                  });
                              Log.d("", response.toString());

                            } catch (JSONException e) {
                              e.printStackTrace();
                            }
                          }

                          @Override
                          public void onError(Exception exception) {
                            VolleyError volleyError = (VolleyError) exception;
                            NetworkResponse response = volleyError.networkResponse;
                            String json = new String(response.data);
                            Log.d("", json);
                            Utilities.dismissLoadingDialog();
                            getActivity().finish();
                          }
                        });
                  }
                }
              });
    }
  }
 /**
  * Called when "get versions" button is clicked.
  *
  * @param v
  */
 public void onGetVersionsClick(View v) {
   sendRequest(RestRequest.getRequestForVersions());
 }
 /**
  * Called when "get resources" button is clicked.
  *
  * @param v
  */
 public void onGetResourcesClick(View v) {
   sendRequest(RestRequest.getRequestForResources(apiVersion));
 }
 /**
  * Called when "describe" button is clicked.
  *
  * @param v
  */
 public void onDescribeClick(View v) {
   String objectType =
       ((EditText) findViewById(R.id.describe_object_type_text)).getText().toString();
   sendRequest(RestRequest.getRequestForDescribe(apiVersion, objectType));
 }
  private void getRecordType() {
    // Getting  Case record Type
    String soql =
        "SELECT Id, Name, DeveloperName, SobjectType FROM RecordType WHERE SObjectType = 'Case' AND DeveloperName = 'License_Request'";
    try {
      restRequest =
          RestRequest.getRequestForQuery(getActivity().getString(R.string.api_version), soql);
      new ClientManager(
              getActivity(),
              SalesforceSDKManager.getInstance().getAccountType(),
              SalesforceSDKManager.getInstance().getLoginOptions(),
              SalesforceSDKManager.getInstance().shouldLogoutWhenTokenRevoked())
          .getRestClient(
              getActivity(),
              new ClientManager.RestClientCallback() {
                @Override
                public void authenticatedRestClient(RestClient client) {
                  if (client == null) {
                    SalesforceSDKManager.getInstance().logout(getActivity());
                    return;
                  } else {
                    client.sendAsync(
                        restRequest,
                        new RestClient.AsyncRequestCallback() {

                          @Override
                          public void onSuccess(RestRequest request, RestResponse result) {
                            try {
                              JSONObject jsonObject = new JSONObject(result.toString());
                              JSONArray jsonArrayRecords =
                                  jsonObject.getJSONArray(JSONConstants.RECORDS);
                              for (int i = 0; i < jsonArrayRecords.length(); i++) {
                                JSONObject jsonRecord = jsonArrayRecords.getJSONObject(i);
                                String objectType = jsonRecord.getString("SobjectType");
                                String DeveloperName = jsonRecord.getString("DeveloperName");
                                if (objectType.equals("Case")
                                    && DeveloperName.equals("License_Request")) {
                                  activity.setCaseRecordTypeId(jsonRecord.getString("Id"));
                                  getCase();
                                }
                              }
                            } catch (JSONException e) {
                              e.printStackTrace();
                            }
                          }

                          @Override
                          public void onError(Exception exception) {
                            VolleyError volleyError = (VolleyError) exception;
                            NetworkResponse response = volleyError.networkResponse;
                            String json = new String(response.data);
                            Log.d("", json);
                            Utilities.dismissLoadingDialog();
                            getActivity().finish();
                          }
                        });
                  }
                }
              });
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
  }
 /**
  * Called when "describe global" button is clicked.
  *
  * @param v
  */
 public void onDescribeGlobalClick(View v) {
   sendRequest(RestRequest.getRequestForDescribeGlobal(apiVersion));
 }