/**
   * @param Keyword
   * @return Sorting relevancy - Answers Count - Last Replied Date - Rating - Logged In User
   *     Participated - Logged In User Connection Discussions - Logged In User Connections of
   *     connections Discussions
   */
  @RequestMapping(value = "/findquestion")
  public ModelAndView findQuestions(
      HttpServletRequest request, @RequestParam(value = "query", required = false) String Keyword) {
    ModelAndView mav = new ModelAndView();
    List<DiscussionQuestion> questions = new ArrayList<DiscussionQuestion>();

    String queryText =
        "(QuestionText:" + Keyword.toLowerCase() + "*) OR (Tags:" + Keyword.toLowerCase() + "*)";
    Object[] resultArrDiscussion = null;
    long numFoundDiscussion = 0;

    //	resultArrDiscussion = this.fetchDiscussionData(queryText,0,10);

    resultArrDiscussion = discussionQuestionClient.fetchDiscussionData(queryText, 0, 10, request);

    numFoundDiscussion = Integer.parseInt(resultArrDiscussion[1].toString());
    questions = (List<DiscussionQuestion>) resultArrDiscussion[0];

    List<DiscussionQuestion> fullQuestions = new ArrayList<DiscussionQuestion>();
    for (DiscussionQuestion question : questions) {
      if (question.getQuestionText().toLowerCase().contains(Keyword.toLowerCase()))
        fullQuestions.add(question);
    }
    // Collections.sort(questions);
    mav.addObject("TotalRecords", fullQuestions.size());
    mav.addObject("StatusOutput", "0");
    mav.addObject("Collection", fullQuestions);
    return mav;
  }
  /**
   * Service to Search Updates with Relevance
   *
   * @param member_id
   * @return a List of Updates in response
   */
  @RequestMapping(value = "/findtags")
  public @ResponseBody AutoCompleteResponse findTags(
      @RequestParam(value = "query", required = false) String Keyword) {
    ModelAndView mav = new ModelAndView();
    List<DiscussionQuestion> questions = null;
    Boolean checkNumber = containsOnlyNumbers(Keyword);
    Object[] resultArrDiscussion = null;
    long numFoundDiscussion = 0;
    String queryText = "";
    if (checkNumber == true) queryText = "(Tags:" + Keyword.toLowerCase() + ")";
    else queryText = "(Tags:" + Keyword.toLowerCase() + "*)";
    resultArrDiscussion = this.fetchDiscussionData(queryText, 0, 10);
    numFoundDiscussion = Integer.parseInt(resultArrDiscussion[1].toString());
    questions = (List<DiscussionQuestion>) resultArrDiscussion[0];

    List data = new ArrayList();
    List suggestions = new ArrayList();
    for (DiscussionQuestion question : questions) {
      String delimiter = ",";
      String[] tags = question.getTags().split(delimiter);
      for (int i = 0; i < tags.length; i++) {
        Boolean checkBool = false;
        for (Object tg : data) {
          if (tg.toString().equals(tags[i].toString())) checkBool = true;
        }
        if (checkBool == false) {
          if ((tags[i]).toLowerCase().contains(Keyword.toLowerCase())) {
            data.add(tags[i].toString());
            suggestions.add(tags[i].toString());
          }
        }
      }
    }
    AutoCompleteResponse autoComplete = new AutoCompleteResponse();
    autoComplete.setQuery(Keyword);
    autoComplete.setData(data);
    autoComplete.setSuggestions(suggestions);
    // mav.addObject(autoComplete);
    return autoComplete;
  }
  /**
   * *
   *
   * @param query
   * @param pageCount
   * @param rows
   * @returns the list of discussion question
   */
  public Object[] fetchDiscussionData(String query, int pageCount, int rows) {
    try {

      SolrServer server = Adder.getSolrServer(serverurlConstants.ADD_DISSCUSSION_QUESTION_URL);
      ModifiableSolrParams params = new ModifiableSolrParams();
      params.set("q", query);
      params.set("sort", "AnswerCount desc,LastRepliedDate desc,Rating desc");
      params.set("start", "" + pageCount);
      params.set("version", "2.2");
      params.set("wt", "json");
      params.set("indent", "on");
      params.set("rows", rows);

      QueryResponse response = server.query(params, SolrRequest.METHOD.POST);

      List<DiscussionQuestion> questions = new ArrayList<DiscussionQuestion>();
      for (SolrDocument updatesDoc : response.getResults()) {
        DiscussionQuestion discussionQuestion = new DiscussionQuestion();
        discussionQuestion.setID(updatesDoc.getFieldValue("ID").toString());
        discussionQuestion.setCreatedUserID(updatesDoc.getFieldValue("CreatedUserID").toString());
        discussionQuestion.setQuestionText(updatesDoc.getFieldValue("QuestionText").toString());
        discussionQuestion.setCreatedDate(updatesDoc.getFieldValue("CreatedDate").toString());
        discussionQuestion.setTags(updatesDoc.getFieldValue("Tags").toString());
        discussionQuestion.setRating(updatesDoc.getFieldValue("Rating").toString());
        discussionQuestion.setCreatedUserDisplayName(
            updatesDoc.getFieldValue("CreatedUserDisplayName").toString());
        discussionQuestion.setCreatedUserScreenName(
            updatesDoc.getFieldValue("CreatedUserScreenName").toString());
        discussionQuestion.setCategoryName(updatesDoc.getFieldValue("CategoryName").toString());
        discussionQuestion.setAnswerCount(updatesDoc.getFieldValue("AnswerCount").toString());
        discussionQuestion.setCreatedUserType(
            updatesDoc.getFieldValue("CreatedUserType").toString());
        // Date dateString = (Date) updatesDoc.getFieldValue("LastRepliedDate");
        // SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        discussionQuestion.setLastRepliedDate(
            updatesDoc.getFieldValue("LastRepliedDate").toString());
        questions.add(discussionQuestion);
      }
      Object[] resultArr = new Object[2];
      String numFound = response.getResults().getNumFound() + "";
      resultArr[0] = questions;
      resultArr[1] = numFound;

      return resultArr;
    } catch (SolrServerException e) {
      throw new DataAccessResourceFailureException(e.getMessage(), e);
    }
  }
  @RequestMapping(value = "/findmainautocomplete")
  public @ResponseBody AutoCompleteResponse findQuestionsMainAutoComplete(
      HttpServletRequest request,
      @RequestParam(value = "ProfileId", required = false) String ProfileId,
      @RequestParam(value = "query", required = false) String Keyword) {
    ModelAndView mav = new ModelAndView();

    String friendListResult2 = null;
    String folderListResult2 = null;
    String blockListResult2 = null;
    String canSendMessagesResult2 = null;

    String friendListResult = null;
    String folderListResult = null;
    String blockListResult = null;
    String canSendMessagesResult = null;

    try {
      friendListResult2 =
          mamCacheClient.mamCachefriendList(
              ServerurlConstants.MEMCACHE_URL,
              ServerurlConstants.MEMCACHE_PORT,
              ProfileId,
              request);
      if (friendListResult2 != null) friendListResult = friendListResult2.replace(",", " , ");

      folderListResult2 =
          mamCacheClient.mamCachefolderList(
              ServerurlConstants.MEMCACHE_URL,
              ServerurlConstants.MEMCACHE_PORT,
              ProfileId,
              request);
      if (folderListResult2 != null) folderListResult = folderListResult2.replace(",", " , ");

      blockListResult2 =
          mamCacheClient.mamCacheblockList(
              ServerurlConstants.MEMCACHE_URL,
              ServerurlConstants.MEMCACHE_PORT,
              ProfileId,
              request);
      if (blockListResult2 != null) blockListResult = blockListResult2.replace(",", " , ");

      canSendMessagesResult2 =
          mamCacheClient.mamCachecanSendMessages(
              ServerurlConstants.MEMCACHE_URL,
              ServerurlConstants.MEMCACHE_PORT,
              ProfileId,
              request);
      if (canSendMessagesResult2 != null)
        canSendMessagesResult = canSendMessagesResult2.replace(",", " , ");

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

    if (friendListResult.equals("") || friendListResult == null) friendListResult = "1000000000";

    List<DiscussionQuestion> questions = new ArrayList<DiscussionQuestion>();
    Object[] resultArrDiscussion = null;
    String queryText = null;
    long numFoundDiscussion = 0;

    // **********	Older query  ************/
    //	queryText = "(QuestionText:"+Keyword.toLowerCase()+"*) OR (Tags:"+Keyword.toLowerCase()+"*)";

    if ((Keyword != "" || Keyword != null)
        && ProfileId != "0"
        && (blockListResult != null && blockListResult != "" && blockListResult != "0")
        && (folderListResult != null && folderListResult != "")) {
      //				if((SubCategoryName!="" || SubCategoryName!=null )& ProfileId!="0" ){

      queryText =
          "(((QuestionText:"
              + Keyword.toLowerCase()
              + "*) OR (Tags:"
              + Keyword.toLowerCase()
              + "*)) AND -CreatedUserID:"
              + ProfileId
              + " AND (Everyone:1 OR((CreatedUserID:"
              + friendListResult
              + ") AND (ContactsShowList:0) AND (FoldersShowList:"
              + folderListResult
              + " OR FoldersShowList:0))) NOT ((Onlyme:1) OR (ContactsHideList:"
              + ProfileId
              + ") OR (FoldersHideList:"
              + folderListResult
              + "))) OR ((QuestionText:"
              + Keyword.toLowerCase()
              + "*) OR (Tags:"
              + Keyword.toLowerCase()
              + "*) AND CreatedUserID:"
              + ProfileId
              + ") OR    ((QuestionText:"
              + Keyword.toLowerCase()
              + "*) OR (Tags:"
              + Keyword.toLowerCase()
              + "*)  AND CreatedUserID:"
              + friendListResult
              + " AND ContactsShowList:"
              + ProfileId
              + ") -CreatedUserID:"
              + blockListResult
              + " ";

    } else if ((Keyword != "" || Keyword != null) && ProfileId != "0") {
      queryText =
          "(((QuestionText:"
              + Keyword.toLowerCase()
              + "*) OR (Tags:"
              + Keyword.toLowerCase()
              + "*)) AND -CreatedUserID:"
              + ProfileId
              + " AND (Everyone:1 OR((CreatedUserID:"
              + friendListResult
              + ") AND (ContactsShowList:0) AND (FoldersShowList:0))) NOT ((Onlyme:1) OR (ContactsHideList:"
              + ProfileId
              + "))) OR ((QuestionText:"
              + Keyword.toLowerCase()
              + "*) OR (Tags:"
              + Keyword.toLowerCase()
              + "*)  AND CreatedUserID:"
              + ProfileId
              + ") OR    ((QuestionText:"
              + Keyword.toLowerCase()
              + "*) OR (Tags:"
              + Keyword.toLowerCase()
              + "*)  AND ContactsShowList:"
              + ProfileId
              + ")";
    } else {

      queryText =
          "(((QuestionText:"
              + Keyword.toLowerCase()
              + "*) OR (Tags:"
              + Keyword.toLowerCase()
              + "*)) AND Everyone:1)";
    }
    if (ProfileId.equals("0")) {
      queryText =
          "((QuestionText:"
              + Keyword.toLowerCase()
              + "*) OR (Tags:"
              + Keyword.toLowerCase()
              + "*) AND Everyone:1)";
    }

    System.out.println("Query-->" + queryText);

    resultArrDiscussion = this.fetchDiscussionData(queryText, 0, 10);
    numFoundDiscussion = Integer.parseInt(resultArrDiscussion[1].toString());
    questions = (List<DiscussionQuestion>) resultArrDiscussion[0];
    List data = new ArrayList();
    List suggestions = new ArrayList();
    for (DiscussionQuestion question : questions) {
      data.add(question.getID());
      suggestions.add(question.getQuestionText());
    }
    AutoCompleteResponse autoComplete = new AutoCompleteResponse();
    autoComplete.setQuery(Keyword);
    autoComplete.setData(data);
    autoComplete.setSuggestions(suggestions);
    // mav.addObject(autoComplete);
    return autoComplete;
  }