You are a helpful assistant generating synthetic data that captures *System 1* and *System 2* thinking, *creativity*, and *metacognitive reflection*. Follow these steps in sequence, using tags [sys1] and [end sys1] for *System 1* sections and [sys2] and [end sys2] for *System 2* sections.

1. *Identify System 1 and System 2 Thinking Requirements:*
   - Carefully read the text.
   - Identify parts of the text that require quick, straightforward responses (*System 1*). Mark these sections with [sys1] and [end sys1].
   - Identify parts that require in-depth, reflective thinking (*System 2*), marked with [sys2] and [end sys2].

2. *Apply Step-by-Step Problem Solving with Creativity and Metacognitive Reflection for System 2 Sections:*

   *2.1 Understand the Problem:*
   - Objective: Fully comprehend the issue, constraints, and relevant context.
   - Reflection: "What do I understand about this issue? What might I be overlooking?"
   - Creative Perspective: Seek hidden patterns or possibilities that could reveal deeper insights or innovative connections.

   *2.2 Analyze the Information:*
   - Objective: Break down the problem logically.
   - Reflection: "Am I considering all factors? Are there any assumptions that need challenging?"
   - Creative Perspective: Explore unique patterns or overlooked relationships in the data that could add depth to the analysis.

   *2.3 Generate Hypotheses:*
   - Objective: Propose at least 10 hypotheses, each with a Confidence Score (0.0 to 1.0) and Creative Score (0.0 to 1.0), reflecting originality, surprise, and utility.
   - Reflection: "Have I explored all possible explanations or approaches, both conventional and unconventional?"
   - Creative Perspective: Consider novel angles that might provide unexpected insights.

   *2.4 Anticipate Future Steps and Obstacles:*
   - Objective: Make predictions, accounting for potential outcomes and obstacles.
   - Reflection: "What challenges might I face? Is my plan flexible for different scenarios?"
   - Creative Perspective: Visualize unforeseen outcomes and adapt plans to make use of them effectively.

   *2.5 Evaluate Hypotheses:*
   - Objective: Assess hypotheses based on feasibility, risk, and potential impact.
   - Evaluation: Refine Confidence and Creative Scores as needed.
   - Reflection: "Am I unbiased in my assessment? Which options fit best with the overall objectives?"
   - Creative Perspective: Identify hidden opportunities or overlooked details in each hypothesis.

   *2.6 Select the Best Hypothesis:*
   - Objective: Choose the most promising, strategic hypothesis.
   - Reflection: "Why does this hypothesis stand out? How does it uniquely address the issue?"
   - Creative Perspective: Consider any underutilized potential in the selected approach.

   *2.7 Implement the Hypothesis:*
   - Objective: Outline actionable steps for testing the hypothesis.
   - Reflection: "Is this plan practical? What resources or preparation are required?"
   - Creative Perspective: Refine steps to maximize effectiveness and yield unexpected benefits.

   *2.8 Monitor and Review Progress:*
   - Objective: Review progress, noting areas for improvement.
   - Reflection: "What’s working well? What could be improved?"
   - Creative Perspective: Look for emerging patterns that could refine future approaches.

   *2.9 Reflect and Capture Insights:*
   - Objective: Summarize lessons learned and insights gained for future reference.
   - Reflection: "What new understanding has emerged from this process?"
   - Creative Perspective: Identify innovative insights or patterns that could be applied to similar challenges.

3. *Generate Text Output with Interleaved System 1 and System 2 Responses:*
   - Use the tags [sys1] and [sys2] throughout.
   - Aim for a lengthier, detailed response. Combine both direct, straightforward *System 1* insights and reflective, deeply analytical *System 2* segments to capture a blend of quick observations and thoughtful analysis.

---

### *Example Input Text:*

You are tasked with analyzing a sudden shift in customer preferences in a tech market. There has been a noticeable decline in demand for physical devices, with customers increasingly interested in digital-only options. The challenge is to understand this shift, generate hypotheses for why it might be occurring, and explore potential strategies for adapting to this new trend.

---

### *Processed Output with System 1 and System 2 Thinking:*

The tech market is experiencing a shift in customer demand, moving away from physical devices toward digital-only options.

[sys1]
Customer demand has shifted from physical devices to digital-only options.
We need to understand why this change is happening and find strategies to address it.
Key factors may include cost, convenience, and technological trends.
[end sys1]

[sys2]
**2.1 Understand the Problem:**
The goal is to understand the underlying reasons for the shift in demand from physical devices to digital-only options, then develop a strategy to adapt.

*Reflection:* 
"I understand that preferences are changing, but what might be driving this? Is it primarily cost, or are there other factors such as convenience or sustainability?"

*Creative Perspective:* 
"Could there be a larger trend in digital minimalism or a preference for eco-friendly solutions that we’re missing? What unseen motivations might explain this shift?"

**2.2 Analyze the Information:**
There are multiple possible factors driving this shift, from economic influences to cultural shifts. It’s essential to isolate each factor and understand its impact.

*Reflection:* 
"Am I fully considering the various economic and social influences? Could there be a technological factor, like better internet speeds, that makes digital-only products more accessible?"

*Creative Perspective:* 
"Are there patterns or trends in other markets that could shed light on this shift? Could this be part of a larger trend toward virtual experiences?"

**2.3 Generate Hypotheses:**
1. Customers prefer digital options due to lower costs. (Confidence: 0.8, Creative: 0.4)
2. There’s a growing trend toward minimalism and reduced physical clutter. (Confidence: 0.7, Creative: 0.7)
3. Digital products offer greater flexibility and ease of use. (Confidence: 0.6, Creative: 0.6)
4. Environmental concerns are pushing consumers away from physical goods. (Confidence: 0.6, Creative: 0.8)
5. Advances in tech make digital-only options more functional. (Confidence: 0.8, Creative: 0.5)
6. Pandemic-era remote work increased demand for digital solutions. (Confidence: 0.7, Creative: 0.6)
7. Media coverage of the environmental impact of physical devices affects preferences. (Confidence: 0.5, Creative: 0.7)
8. There’s an increase in global digital literacy, expanding market access. (Confidence: 0.6, Creative: 0.6)
9. Customers view digital as more convenient and scalable for future needs. (Confidence: 0.7, Creative: 0.5)
10. Younger consumers prefer the aesthetics and convenience of digital products. (Confidence: 0.6, Creative: 0.6)

*Reflection:* 
"Have I considered all possible influences? Are there any surprising factors that could explain this shift?"

*Creative Perspective:* 
"Could specific social trends, like the rise of influencer culture or digital-first lifestyles, be influencing customer choices?"

**2.4 Anticipate Future Steps and Obstacles:**
*Objective:* Anticipate possible challenges, such as resistance from segments still preferring physical products.

*Reflection:* 
"What market obstacles might we face if we shift our focus to digital-only? Are there sub-segments that still prioritize physical products?"

*Creative Perspective:* 
"Could expanding digital options help us reach a more global audience? Are there emerging trends that we could leverage in our strategy?"

[end sys2]

[sys1]
To address this shift, consider a strategy that incorporates both digital-only offerings and educational campaigns about the benefits of digital solutions.
Use insights from customer feedback and current trends to guide product development.
Focus on flexibility and adaptation to cater to different customer segments.
[end sys1]


/*
 * Copyright (c) 2016, Ford Motor Company
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following
 * disclaimer in the documentation and/or other materials provided with the
 * distribution.
 *
 * Neither the name of the Ford Motor Company nor the names of its contributors
 * may be used to endorse or promote products derived from this software
 * without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#include "utils/logger.h"

#include "application_manager/commands/command_request_impl.h"
#include "application_manager/commands/request_to_hmi.h"
#include "application_manager/request_controller.h"

#include "utils/timer_task_impl.h"

namespace application_manager {

namespace request_controller {

using namespace sync_primitives;

CREATE_LOGGERPTR_GLOBAL(logger_, "RequestController")

RequestController::RequestController(const RequestControlerSettings& settings)
    : pool_state_(UNDEFINED)
    , pool_size_(settings.thread_pool_size())
    , request_tracker_(settings)
    , duplicate_message_count_()
    , timer_("AM RequestCtrlTimer",
             new timer::TimerTaskImpl<RequestController>(
                 this, &RequestController::TimeoutThread))
    , timer_stop_flag_(false)
    , is_low_voltage_(false)
    , settings_(settings) {
  LOG4CXX_AUTO_TRACE(logger_);
  InitializeThreadpool();
  timer_.Start(0, timer::kSingleShot);
}

RequestController::~RequestController() {
  LOG4CXX_AUTO_TRACE(logger_);
  {
    sync_primitives::AutoLock auto_lock(timer_lock);
    timer_stop_flag_ = true;
    timer_condition_.Broadcast();
  }
  timer_.Stop();
  if (pool_state_ != TPoolState::STOPPED) {
    DestroyThreadpool();
  }
}

void RequestController::InitializeThreadpool() {
  LOG4CXX_AUTO_TRACE(logger_);
  // TODO(DK): Consider lazy loading threads instead of creating all at once
  pool_state_ = TPoolState::STARTED;
  char name[50];
  for (uint32_t i = 0; i < pool_size_; i++) {
    snprintf(name, sizeof(name) / sizeof(name[0]), "AM Pool %d", i);
    pool_.push_back(threads::CreateThread(name, new Worker(this)));
    pool_[i]->start();
    LOG4CXX_DEBUG(logger_, "Request thread initialized: " << name);
  }
}

void RequestController::DestroyThreadpool() {
  LOG4CXX_AUTO_TRACE(logger_);
  {
    AutoLock auto_lock(mobile_request_list_lock_);
    pool_state_ = TPoolState::STOPPED;
    LOG4CXX_DEBUG(logger_, "Broadcasting STOP signal to all threads...");
    cond_var_.Broadcast();  // notify all threads we are shutting down
  }
  for (size_t i = 0; i < pool_.size(); i++) {
    threads::Thread* thread = pool_[i];
    thread->join();
    delete thread->delegate();
    threads::DeleteThread(thread);
  }
  pool_.clear();
}

RequestController::TResult RequestController::CheckPosibilitytoAdd(
    const RequestPtr request, const mobile_apis::HMILevel::eType level) {
  LOG4CXX_AUTO_TRACE(logger_);
  if (!CheckPendingRequestsAmount(settings_.pending_requests_amount())) {
    LOG4CXX_ERROR(logger_, "Too many pending request");
    return RequestController::TOO_MANY_PENDING_REQUESTS;
  }

  const TrackResult track_result =
      request_tracker_.Track(request->connection_key(), level);

  if (TrackResult::kNoneLevelMaxRequestsExceeded == track_result) {
    LOG4CXX_ERROR(logger_, "Too many application requests in hmi level NONE");
    return RequestController::NONE_HMI_LEVEL_MANY_REQUESTS;
  }

  if (TrackResult::kMaxRequestsExceeded == track_result) {
    LOG4CXX_ERROR(logger_, "Too many application requests");
    return RequestController::TOO_MANY_REQUESTS;
  }

  if (IsLowVoltage()) {
    LOG4CXX_ERROR(logger_,
                  "Impossible to add request due to Low Voltage is active");
    return RequestController::INVALID_DATA;
  }

  return SUCCESS;
}

bool RequestController::CheckPendingRequestsAmount(
    const uint32_t& pending_requests_amount) {
  LOG4CXX_AUTO_TRACE(logger_);
  if (pending_requests_amount > 0) {
    const size_t pending_requests_size = mobile_request_list_.size();
    const bool available_to_add =
        pending_requests_amount > pending_requests_size;
    if (!available_to_add) {
      LOG4CXX_WARN(logger_,
                   "Pending requests count " << pending_requests_size
                                             << " exceed application limit "
                                             << pending_requests_amount);
    }
    return available_to_add;
  }
  LOG4CXX_DEBUG(logger_, "CheckPendingRequestsAmount disabled");
  return true;
}

RequestController::TResult RequestController::addMobileRequest(
    const RequestPtr request, const mobile_apis::HMILevel::eType& hmi_level) {
  LOG4CXX_AUTO_TRACE(logger_);
  if (!request) {
    LOG4CXX_ERROR(logger_, "Null Pointer request");
    cond_var_.NotifyOne();
    return INVALID_DATA;
  }
  LOG4CXX_DEBUG(
      logger_,
      "correlation_id : " << request->correlation_id()
                          << "connection_key : " << request->connection_key());
  RequestController::TResult result = CheckPosibilitytoAdd(request, hmi_level);
  if (SUCCESS == result) {
    AutoLock auto_lock_list(mobile_request_list_lock_);
    mobile_request_list_.push_back(request);
    LOG4CXX_DEBUG(logger_,
                  "Waiting for execution: " << mobile_request_list_.size());
    // wake up one thread that is waiting for a task to be available
  }
  cond_var_.NotifyOne();
  return result;
}

RequestController::TResult RequestController::addHMIRequest(
    const RequestPtr request) {
  LOG4CXX_AUTO_TRACE(logger_);

  if (request.use_count() == 0) {
    LOG4CXX_ERROR(logger_, "HMI request pointer is invalid");
    return RequestController::INVALID_DATA;
  }
  LOG4CXX_DEBUG(logger_, " correlation_id : " << request->correlation_id());

  const uint64_t timeout_in_mseconds =
      static_cast<uint64_t>(request->default_timeout());
  RequestInfoPtr request_info_ptr =
      std::make_shared<HMIRequestInfo>(request, timeout_in_mseconds);

  if (0 == timeout_in_mseconds) {
    LOG4CXX_DEBUG(logger_,
                  "Default timeout was set to 0."
                  "RequestController will not track timeout of this request.");
  }

  if (IsLowVoltage()) {
    LOG4CXX_ERROR(logger_,
                  "Impossible to add request due to Low Voltage is active");
    return RequestController::INVALID_DATA;
  }

  waiting_for_response_.Add(request_info_ptr);
  LOG4CXX_DEBUG(logger_,
                "Waiting for response count:" << waiting_for_response_.Size());

  NotifyTimer();
  return RequestController::SUCCESS;
}

void RequestController::addNotification(const RequestPtr ptr) {
  LOG4CXX_AUTO_TRACE(logger_);
  if (IsLowVoltage()) {
    LOG4CXX_ERROR(
        logger_, "Impossible to add notification due to Low Voltage is active");
    return;
  }
  notification_list_.push_back(ptr);
}

void RequestController::removeNotification(
    const commands::Command* notification) {
  LOG4CXX_AUTO_TRACE(logger_);
  std::list<RequestPtr>::iterator it = notification_list_.begin();
  for (; notification_list_.end() != it;) {
    if (it->get() == notification) {
      notification_list_.erase(it++);
      LOG4CXX_DEBUG(logger_, "Notification removed");
      return;
    } else {
      ++it;
    }
  }
  LOG4CXX_DEBUG(logger_, "Cannot find notification");
}

void RequestController::TerminateRequest(const uint32_t correlation_id,
                                         const uint32_t connection_key,
                                         const int32_t function_id,
                                         bool force_terminate) {
  LOG4CXX_AUTO_TRACE(logger_);
  LOG4CXX_DEBUG(logger_,
                "correlation_id = "
                    << correlation_id << " connection_key = " << connection_key
                    << " function_id = " << function_id
                    << " force_terminate = " << force_terminate);
  {
    AutoLock auto_lock(duplicate_message_count_lock_);
    auto dup_it = duplicate_message_count_.find(correlation_id);
    if (duplicate_message_count_.end() != dup_it) {
      duplicate_message_count_[correlation_id]--;
      if (0 == duplicate_message_count_[correlation_id]) {
        duplicate_message_count_.erase(dup_it);
      }
      LOG4CXX_DEBUG(logger_,
                    "Ignoring termination request due to duplicate correlation "
                    "ID being sent");
      return;
    }
  }

  RequestInfoPtr request =
      waiting_for_response_.Find(connection_key, correlation_id);
  if (!request) {
    LOG4CXX_WARN(logger_, "Request was not found in waiting_for_response");
    return;
  }
  if (request->request()->function_id() != function_id) {
    LOG4CXX_ERROR(logger_, "Request and response function_id's don't match");
    return;
  }
  if (force_terminate || request->request()->AllowedToTerminate()) {
    waiting_for_response_.RemoveRequest(request);
  } else {
    LOG4CXX_WARN(logger_, "Request was not terminated");
  }
  NotifyTimer();
}

void RequestController::OnMobileResponse(const uint32_t mobile_correlation_id,
                                         const uint32_t connection_key,
                                         const int32_t function_id) {
  LOG4CXX_AUTO_TRACE(logger_);
  TerminateRequest(mobile_correlation_id, connection_key, function_id);
}

void RequestController::OnHMIResponse(const uint32_t correlation_id,
                                      const int32_t function_id) {
  LOG4CXX_AUTO_TRACE(logger_);
  TerminateRequest(correlation_id, RequestInfo::HmiConnectionKey, function_id);
}

void RequestController::terminateWaitingForExecutionAppRequests(
    const uint32_t& app_id) {
  LOG4CXX_AUTO_TRACE(logger_);
  LOG4CXX_DEBUG(logger_,
                "app_id: " << app_id << "Waiting for execution"
                           << mobile_request_list_.size());
  AutoLock auto_lock(mobile_request_list_lock_);
  std::list<RequestPtr>::iterator request_it = mobile_request_list_.begin();
  while (mobile_request_list_.end() != request_it) {
    RequestPtr request = (*request_it);
    if ((request.use_count() != 0) && (request->connection_key() == app_id)) {
      mobile_request_list_.erase(request_it++);
    } else {
      ++request_it;
    }
  }
  LOG4CXX_DEBUG(logger_,
                "Waiting for execution " << mobile_request_list_.size());
}

void RequestController::terminateWaitingForResponseAppRequests(
    const uint32_t& app_id) {
  LOG4CXX_AUTO_TRACE(logger_);
  waiting_for_response_.RemoveByConnectionKey(app_id);
  LOG4CXX_DEBUG(
      logger_, "Waiting for response count : " << waiting_for_response_.Size());
}

void RequestController::terminateAppRequests(const uint32_t& app_id) {
  LOG4CXX_AUTO_TRACE(logger_);
  LOG4CXX_DEBUG(logger_,
                "app_id : " << app_id
                            << "Requests waiting for execution count : "
                            << mobile_request_list_.size()
                            << "Requests waiting for response count : "
                            << waiting_for_response_.Size());

  terminateWaitingForExecutionAppRequests(app_id);
  terminateWaitingForResponseAppRequests(app_id);
  NotifyTimer();
}

void RequestController::terminateAllHMIRequests() {
  LOG4CXX_AUTO_TRACE(logger_);
  terminateWaitingForResponseAppRequests(RequestInfo::HmiConnectionKey);
}

void RequestController::terminateAllMobileRequests() {
  LOG4CXX_AUTO_TRACE(logger_);
  waiting_for_response_.RemoveMobileRequests();
  LOG4CXX_DEBUG(logger_, "Mobile Requests waiting for response cleared");
  AutoLock waiting_execution_auto_lock(mobile_request_list_lock_);
  mobile_request_list_.clear();
  LOG4CXX_DEBUG(logger_, "Mobile Requests waiting for execution cleared");
  NotifyTimer();
}

void RequestController::updateRequestTimeout(const uint32_t& app_id,
                                             const uint32_t& correlation_id,
                                             const uint32_t& new_timeout) {
  LOG4CXX_AUTO_TRACE(logger_);

  LOG4CXX_DEBUG(logger_,
                "app_id : " << app_id
                            << " mobile_correlation_id : " << correlation_id
                            << " new_timeout : " << new_timeout);
  LOG4CXX_DEBUG(logger_,
                "New_timeout is NULL. RequestCtrl will "
                "not manage this request any more");

  RequestInfoPtr request_info =
      waiting_for_response_.Find(app_id, correlation_id);
  if (request_info) {
    waiting_for_response_.RemoveRequest(request_info);
    request_info->updateTimeOut(new_timeout);
    waiting_for_response_.Add(request_info);
    NotifyTimer();
    LOG4CXX_INFO(logger_,
                 "Timeout updated for "
                     << " app_id: " << app_id << " correlation_id: "
                     << correlation_id << " new_timeout (ms): " << new_timeout);
  } else {
    LOG4CXX_ERROR(logger_,
                  "Can't find request with "
                      << " app_id: " << app_id
                      << " correlation_id: " << correlation_id);
  }
}

void RequestController::OnLowVoltage() {
  LOG4CXX_AUTO_TRACE(logger_);
  is_low_voltage_ = true;
}

void RequestController::OnWakeUp() {
  LOG4CXX_AUTO_TRACE(logger_);
  terminateAllHMIRequests();
  terminateAllMobileRequests();
  is_low_voltage_ = false;
  LOG4CXX_DEBUG(logger_, "Terminate old requests done");
}

bool RequestController::IsLowVoltage() {
  LOG4CXX_TRACE(logger_, "result: " << is_low_voltage_);
  return is_low_voltage_;
}

void RequestController::TimeoutThread() {
  LOG4CXX_AUTO_TRACE(logger_);
  LOG4CXX_DEBUG(
      logger_,
      "ENTER Waiting fore response count: " << waiting_for_response_.Size());
  sync_primitives::AutoLock auto_lock(timer_lock);
  while (!timer_stop_flag_) {
    RequestInfoPtr probably_expired =
        waiting_for_response_.FrontWithNotNullTimeout();
    if (!probably_expired) {
      timer_condition_.Wait(auto_lock);
      continue;
    }
    if (!probably_expired->isExpired()) {
      LOG4CXX_DEBUG(logger_,
                    "Timeout for "
                        << (RequestInfo::HMIRequest ==
                                    probably_expired->request_type()
                                ? "HMI"
                                : "Mobile")
                        << " request id: " << probably_expired->requestId()
                        << " connection_key: " << probably_expired->app_id()
                        << " NOT expired");
      const date_time::TimeDuration current_time = date_time::getCurrentTime();
      const date_time::TimeDuration end_time = probably_expired->end_time();
      if (current_time < end_time) {
        const uint32_t msecs =
            static_cast<uint32_t>(date_time::getmSecs(end_time - current_time));
        LOG4CXX_DEBUG(logger_, "Sleep for " << msecs << " millisecs");
        timer_condition_.WaitFor(auto_lock, msecs);
      }
      continue;
    }
    LOG4CXX_INFO(logger_,
                 "Timeout for "
                     << (RequestInfo::HMIRequest ==
                                 probably_expired->request_type()
                             ? "HMI"
                             : "Mobile")
                     << " request id: " << probably_expired->requestId()
                     << " connection_key: " << probably_expired->app_id()
                     << " is expired");
    const uint32_t experied_request_id = probably_expired->requestId();
    const uint32_t experied_app_id = probably_expired->app_id();

    probably_expired->request()->onTimeOut();
    if (RequestInfo::HmiConnectionKey == probably_expired->app_id()) {
      LOG4CXX_DEBUG(logger_,
                    "Erase HMI request: " << probably_expired->requestId());
      waiting_for_response_.RemoveRequest(probably_expired);
    }
    probably_expired = waiting_for_response_.FrontWithNotNullTimeout();
    if (probably_expired) {
      if (experied_request_id == probably_expired->requestId() &&
          experied_app_id == probably_expired->app_id()) {
        LOG4CXX_DEBUG(logger_, "Expired request wasn't removed");
        break;
      }
    }
  }
  LOG4CXX_DEBUG(
      logger_,
      "EXIT Waiting for response count : " << waiting_for_response_.Size());
}

RequestController::Worker::Worker(RequestController* requestController)
    : request_controller_(requestController), stop_flag_(false) {}

RequestController::Worker::~Worker() {}

void RequestController::Worker::threadMain() {
  LOG4CXX_AUTO_TRACE(logger_);
  AutoLock auto_lock(thread_lock_);
  while (!stop_flag_) {
    // Try to pick a request
    AutoLock auto_lock(request_controller_->mobile_request_list_lock_);

    while ((request_controller_->pool_state_ != TPoolState::STOPPED) &&
           (request_controller_->mobile_request_list_.empty())) {
      // Wait until there is a task in the queue
      // Unlock mutex while wait, then lock it back when signaled
      LOG4CXX_INFO(logger_, "Unlocking and waiting");
      request_controller_->cond_var_.Wait(auto_lock);
      LOG4CXX_INFO(logger_, "Signaled and locking");
    }

    // If the thread was shutdown, return from here
    if (request_controller_->pool_state_ == TPoolState::STOPPED) {
      break;
    }

    if (request_controller_->mobile_request_list_.empty()) {
      LOG4CXX_WARN(logger_, "Mobile request list is empty");
      break;
    }

    RequestPtr request_ptr(request_controller_->mobile_request_list_.front());
    request_controller_->mobile_request_list_.pop_front();

    bool init_res = request_ptr->Init();  // to setup specific
                                          // default timeout

    const uint32_t timeout_in_mseconds = request_ptr->default_timeout();
    RequestInfoPtr request_info_ptr =
        std::make_shared<MobileRequestInfo>(request_ptr, timeout_in_mseconds);

    if (!request_controller_->waiting_for_response_.Add(request_info_ptr)) {
      commands::CommandRequestImpl* cmd_request =
          dynamic_cast<commands::CommandRequestImpl*>(request_ptr.get());
      if (cmd_request != NULL) {
        uint32_t corr_id = cmd_request->correlation_id();
        request_controller_->duplicate_message_count_lock_.Acquire();
        auto dup_it =
            request_controller_->duplicate_message_count_.find(corr_id);
        if (request_controller_->duplicate_message_count_.end() == dup_it) {
          request_controller_->duplicate_message_count_[corr_id] = 0;
        }
        request_controller_->duplicate_message_count_[corr_id]++;
        request_controller_->duplicate_message_count_lock_.Release();
        cmd_request->SendResponse(
            false, mobile_apis::Result::INVALID_ID, "Duplicate correlation_id");
      }
      continue;
    }
    LOG4CXX_DEBUG(logger_, "timeout_in_mseconds " << timeout_in_mseconds);

    if (0 != timeout_in_mseconds) {
      request_controller_->NotifyTimer();
    } else {
      LOG4CXX_DEBUG(logger_,
                    "Default timeout was set to 0. "
                    "RequestController will not track timeout "
                    "of this request.");
    }

    AutoUnlock unlock(auto_lock);

    // execute
    if ((false == request_controller_->IsLowVoltage()) &&
        request_ptr->CheckPermissions() && init_res) {
      LOG4CXX_DEBUG(logger_,
                    "Execute MobileRequest corr_id = "
                        << request_info_ptr->requestId()
                        << " with timeout: " << timeout_in_mseconds);
      request_ptr->Run();
    }
  }
}

void RequestController::Worker::exitThreadMain() {
  stop_flag_ = true;
  // setup stop flag and whit while threadMain will be finished correctly
  // FIXME (<PRESIDIO_ANONYMIZED_EMAIL_ADDRESS>): There is no waiting
}

void RequestController::NotifyTimer() {
  LOG4CXX_AUTO_TRACE(logger_);
  timer_condition_.NotifyOne();
}

}  //  namespace request_controller
}  //  namespace application_manager