package com.ikea.shared.shopping.service;

import android.content.Context;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import com.ikea.shared.AppConfigData;
import com.ikea.shared.AppConfigManager;
import com.ikea.shared.BaseService;
import com.ikea.shared.BaseService.NetworkCaller;
import com.ikea.shared.WLEngine;
import com.ikea.shared.WLEngine.GenericInvokeRequestWlResponseListener;
import com.ikea.shared.WLEngine.WlException;
import com.ikea.shared.analytics.UsageTracker;
import com.ikea.shared.browse.model.ProductListing;
import com.ikea.shared.cart.ShoppingCart;
import com.ikea.shared.cart.model.ShoppingBagItem;
import com.ikea.shared.cart.model.ShoppingBagItemList;
import com.ikea.shared.cart.model.ShoppingBagSection;
import com.ikea.shared.cart.model.ShoppingBags;
import com.ikea.shared.cart.model.SyncEventModel;
import com.ikea.shared.network.KompisRequest;
import com.ikea.shared.network.RequestUtil;
import com.ikea.shared.network.WLRequest;
import com.ikea.shared.products.model.Quantity;
import com.ikea.shared.products.model.RetailItemCommChild;
import com.ikea.shared.products.model.RetailItemCommChildList;
import com.ikea.shared.products.model.RetailItemCommPrice;
import com.ikea.shared.products.model.RetailItemCommPriceList;
import com.ikea.shared.products.model.RetailItemCommunication;
import com.ikea.shared.products.service.ProductService;
import com.ikea.shared.products.service.ProductService.STOCK_STATUS;
import com.ikea.shared.shopping.event.SessionExpiredEvent;
import com.ikea.shared.shopping.event.ShoppingListRefreshEvent;
import com.ikea.shared.shopping.event.StartSyncEvent;
import com.ikea.shared.stores.model.RetailItemAvailability;
import com.ikea.shared.stores.model.StockAvailability;
import com.ikea.shared.stores.model.StockAvailabilityResponse;
import com.ikea.shared.stores.model.StoreRef;
import com.ikea.shared.user.event.LoginSyncFailedEvent;
import com.ikea.shared.user.event.LoginSyncResultEvent;
import com.ikea.shared.user.event.SyncFailedEvent;
import com.ikea.shared.user.model.SessionContext;
import com.ikea.shared.user.model.User;
import com.ikea.shared.user.model.UserSessionResponse;
import com.ikea.shared.user.service.UserService;
import com.ikea.shared.util.AppExecutors;
import com.ikea.shared.util.Constant;
import com.ikea.shared.util.L;
import com.ikea.shared.util.ServiceCallback;
import com.squareup.otto.Bus;
import com.worklight.wlclient.api.WLFailResponse;
import com.worklight.wlclient.api.WLResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

public final class ShoppingCartService extends BaseService
{
  public static final int INVALID_BAGID_CODE = 500;
  public static final int LOGIN_SESSION_CHECK_FAILED = 2;
  public static final int LOGIN_SESSION_EXPIRED = 1;
  public static final int LOGIN_SESSION_VALID = 0;
  private static final String ROOT_PATH = "sync_cart_service";
  public static final int SESSION_EXPIRES_CODE = 404;
  private static ShoppingCartService instance;
  private final ExecutorService mExecutorService = AppExecutors.highPrio();
  private Future<Boolean> mFuture;
  private boolean mLoginSyncInPocess;
  private final PersistentQueue mQueue;
  private String mSLMergeResult = "";
  private boolean mSyncInPocess;
  private List<ShoppingBagItem> offlineItemList = new ArrayList();
  private boolean showSLMergeResult = false;

  private ShoppingCartService(Context paramContext)
  {
    super(paramContext);
    this.mQueue = new PersistentQueue(paramContext, "sync_cart_service");
    loadEventQueueIfRequired();
  }

  private RetailItemCommunication GetEquivalentNewItem(RetailItemCommunication paramRetailItemCommunication, List<RetailItemCommunication> paramList)
  {
    Iterator localIterator = paramList.iterator();
    while (localIterator.hasNext())
    {
      RetailItemCommunication localRetailItemCommunication = (RetailItemCommunication)localIterator.next();
      if (paramRetailItemCommunication.getItemNo().equalsIgnoreCase(localRetailItemCommunication.getItemNo()))
        return localRetailItemCommunication;
    }
    return null;
  }

  private void ResetBagID()
  {
    ShoppingCart.i(this.mContext).setShoppingBagId("");
  }

  private ShoppingBags addItemWLSync(SyncEventModel paramSyncEventModel, User paramUser, String paramString)
    throws Exception
  {
    ShoppingBagSection localShoppingBagSection = createPostData(paramSyncEventModel.getItems());
    return invokeRequestWlResponseListener(RequestUtil.getAddItemRequestWL(this.mContext, paramUser.getSessionContext().getEmailAddress(), ShoppingCart.i(this.mContext).getShoppingBagId(), localShoppingBagSection, paramUser.getSessionKey()));
  }

  private ShoppingBagSection createPostData(List<ShoppingBagItem> paramList)
  {
    if ((paramList != null) && (!paramList.isEmpty()))
    {
      ShoppingBagSection localShoppingBagSection = new ShoppingBagSection();
      ShoppingBagItemList localShoppingBagItemList = new ShoppingBagItemList();
      localShoppingBagSection.setShoppingBagItemList(localShoppingBagItemList);
      localShoppingBagItemList.setShoppingBagItem(new ArrayList());
      if (paramList != null)
        localShoppingBagItemList.setShoppingBagItem(paramList);
      return localShoppingBagSection;
    }
    return null;
  }

  private ProductListing getGuestShoppingBagsSync(String paramString)
    throws Exception
  {
    ShoppingBagSection localShoppingBagSection = createPostData(getPostDataforSync(false));
    KompisRequest localKompisRequest = RequestUtil.getLatestGuestShoppingListRequest(this.mContext, localShoppingBagSection);
    return (ProductListing)new BaseService.NetworkCaller(this, ProductListing.class, this.mContext).execute(localKompisRequest);
  }

  private RetailItemCommunication getLocalItem(String paramString, Collection<RetailItemCommunication> paramCollection)
  {
    Iterator localIterator = paramCollection.iterator();
    while (localIterator.hasNext())
    {
      RetailItemCommunication localRetailItemCommunication = (RetailItemCommunication)localIterator.next();
      if (localRetailItemCommunication.getItemNo().equalsIgnoreCase(paramString))
        return localRetailItemCommunication;
    }
    return null;
  }

  private int getLocalQuantity(String paramString, Collection<RetailItemCommunication> paramCollection)
  {
    Iterator localIterator = paramCollection.iterator();
    while (localIterator.hasNext())
    {
      RetailItemCommunication localRetailItemCommunication = (RetailItemCommunication)localIterator.next();
      if (localRetailItemCommunication.getItemNo().equalsIgnoreCase(paramString))
        return (int)Float.parseFloat(localRetailItemCommunication.getQuantity().getQuantity());
    }
    return 0;
  }

  private Quantity getQuantity(String paramString, Collection<RetailItemCommunication> paramCollection)
  {
    Iterator localIterator = paramCollection.iterator();
    while (localIterator.hasNext())
    {
      RetailItemCommunication localRetailItemCommunication = (RetailItemCommunication)localIterator.next();
      if (localRetailItemCommunication.getItemNo().equalsIgnoreCase(paramString))
        return localRetailItemCommunication.getQuantity();
    }
    return null;
  }

  private ShoppingBags getShoppingBagsWLSync(User paramUser, String paramString1, String paramString2)
    throws Exception
  {
    return invokeRequestWlResponseListener(RequestUtil.getShoppingBagRequestWL(this.mContext, paramUser.getSessionContext().getEmailAddress(), paramString2, paramUser.getSessionKey()));
  }

  public static final ShoppingCartService i(Context paramContext)
  {
    try
    {
      if (instance == null)
        instance = new ShoppingCartService(paramContext);
      ShoppingCartService localShoppingCartService = instance;
      return localShoppingCartService;
    }
    finally
    {
    }
  }

  private UserSessionResponse invokeLoginSessionValidRequestWlResponseListener(WLRequest paramWLRequest)
    throws InterruptedException
  {
    final CountDownLatch localCountDownLatch = new CountDownLatch(1);
    WLEngine.GenericInvokeRequestWlResponseListener local4 = new WLEngine.GenericInvokeRequestWlResponseListener(null, UserSessionResponse.class)
    {
      public void onFailure(WLFailResponse paramAnonymousWLFailResponse)
      {
        Log.d("KOMPIS", "WL call fail " + paramAnonymousWLFailResponse.getStatus());
        this.mResponse = super.parseResponse(paramAnonymousWLFailResponse);
        localCountDownLatch.countDown();
      }

      public void onSuccess(WLResponse paramAnonymousWLResponse)
      {
        this.mResponse = super.parseResponse(paramAnonymousWLResponse);
        localCountDownLatch.countDown();
      }
    };
    boolean bool = WLEngine.i(this.mContext).invoke(paramWLRequest, local4);
    UserSessionResponse localUserSessionResponse = null;
    if (bool)
    {
      localCountDownLatch.await();
      if ((local4.getResponse() != null) && (!((UserSessionResponse)local4.getResponse()).isSuccessful()))
        Log.d("KOMPIS", "WL call fail " + ((UserSessionResponse)local4.getResponse()).getErrorCode());
      localUserSessionResponse = (UserSessionResponse)local4.getResponse();
    }
    return localUserSessionResponse;
  }

  private ShoppingBags invokeRequestWlResponseListener(WLRequest paramWLRequest)
    throws InterruptedException
  {
    final CountDownLatch localCountDownLatch = new CountDownLatch(1);
    WLEngine.GenericInvokeRequestWlResponseListener local3 = new WLEngine.GenericInvokeRequestWlResponseListener(null, ShoppingBags.class)
    {
      public void onFailure(WLFailResponse paramAnonymousWLFailResponse)
      {
        Log.d("KOMPIS", "WL call fail " + paramAnonymousWLFailResponse.getStatus());
        this.mResponse = super.parseResponse(paramAnonymousWLFailResponse);
        localCountDownLatch.countDown();
      }

      public void onSuccess(WLResponse paramAnonymousWLResponse)
      {
        this.mResponse = super.parseResponse(paramAnonymousWLResponse);
        localCountDownLatch.countDown();
      }
    };
    boolean bool = WLEngine.i(this.mContext).invoke(paramWLRequest, local3);
    ShoppingBags localShoppingBags = null;
    if (bool)
    {
      localCountDownLatch.await();
      if ((local3.getResponse() != null) && (!((ShoppingBags)local3.getResponse()).isSuccessful()))
        Log.d("KOMPIS", "WL call fail " + ((ShoppingBags)local3.getResponse()).getErrorCode());
      localShoppingBags = (ShoppingBags)local3.getResponse();
    }
    return localShoppingBags;
  }

  private boolean isChildCollected(String paramString, RetailItemCommunication paramRetailItemCommunication)
  {
    if ((paramRetailItemCommunication != null) && (paramRetailItemCommunication.getRetailItemCommChildList() != null) && (paramRetailItemCommunication.getRetailItemCommChildList().getRetailItemCommChild() != null))
    {
      Iterator localIterator = paramRetailItemCommunication.getRetailItemCommChildList().getRetailItemCommChild().iterator();
      while (localIterator.hasNext())
      {
        RetailItemCommChild localRetailItemCommChild = (RetailItemCommChild)localIterator.next();
        if (localRetailItemCommChild.getItemNo().equalsIgnoreCase(paramString))
          return localRetailItemCommChild.isCollected();
      }
    }
    return false;
  }

  private boolean isCollected(String paramString, Collection<RetailItemCommunication> paramCollection)
  {
    Iterator localIterator = paramCollection.iterator();
    while (localIterator.hasNext())
    {
      RetailItemCommunication localRetailItemCommunication = (RetailItemCommunication)localIterator.next();
      if (localRetailItemCommunication.getItemNo().equalsIgnoreCase(paramString))
        return localRetailItemCommunication.isCollected();
    }
    return false;
  }

  private int isLoginSessionValid(User paramUser)
    throws Exception
  {
    UserSessionResponse localUserSessionResponse = invokeLoginSessionValidRequestWlResponseListener(RequestUtil.getCheckValidSessionRequestWL(this.mContext, paramUser.getSessionKey()));
    if ((localUserSessionResponse != null) && (localUserSessionResponse.isSuccessful()))
      return 0;
    if ((localUserSessionResponse != null) && (localUserSessionResponse.getErrorCode() == 404))
      return 1;
    return 2;
  }

  private boolean isLoworOutOfStock(RetailItemCommunication paramRetailItemCommunication)
  {
    ProductService.STOCK_STATUS localSTOCK_STATUS = ProductService.i(this.mContext).getStockStatus(paramRetailItemCommunication);
    return (localSTOCK_STATUS.equals(ProductService.STOCK_STATUS.LOW_STOCK)) || (localSTOCK_STATUS.equals(ProductService.STOCK_STATUS.NOT_STOCK));
  }

  private boolean isNotPresentinItems(RetailItemCommunication paramRetailItemCommunication, List<RetailItemCommunication> paramList)
  {
    Iterator localIterator = paramList.iterator();
    while (localIterator.hasNext())
    {
      RetailItemCommunication localRetailItemCommunication = (RetailItemCommunication)localIterator.next();
      if (paramRetailItemCommunication.getItemNo().equalsIgnoreCase(localRetailItemCommunication.getItemNo()))
        return false;
    }
    return true;
  }

  private boolean isPriceUpdated(RetailItemCommunication paramRetailItemCommunication1, RetailItemCommunication paramRetailItemCommunication2)
  {
    RetailItemCommPriceList localRetailItemCommPriceList1 = paramRetailItemCommunication1.getRetailItemCommPriceList();
    RetailItemCommPriceList localRetailItemCommPriceList2 = paramRetailItemCommunication2.getRetailItemCommPriceList();
    if ((localRetailItemCommPriceList1 != null) && (localRetailItemCommPriceList2 != null))
    {
      List localList1 = localRetailItemCommPriceList1.getRetailItemCommPrice();
      List localList2 = localRetailItemCommPriceList2.getRetailItemCommPrice();
      if ((localList1 != null) && (localList2 != null))
      {
        if (localList1.size() == localList2.size())
        {
          int i = localList1.size();
          for (int j = 0; j < i; j++)
            if (((RetailItemCommPrice)localList1.get(j)).getPrice() != ((RetailItemCommPrice)localList2.get(j)).getPrice())
              return true;
        }
        return true;
      }
    }
    return false;
  }

  private void loadEventQueueIfRequired()
  {
    if (!this.mQueue.isLoaded())
      this.mQueue.load();
  }

  private void notifyLoginSync(final ShoppingBags paramShoppingBags)
  {
    if ((paramShoppingBags != null) && (paramShoppingBags.isSuccessful()))
    {
      if (paramShoppingBags.isBagCreated())
        UsageTracker.i().createShoppingList(this.mContext);
      if (TextUtils.isEmpty(paramShoppingBags.getMergevalue()));
    }
    try
    {
      this.mHandler.post(new Runnable()
      {
        public void run()
        {
          ShoppingCartService.this.setSLMergeResult(paramShoppingBags.getMergevalue());
          ShoppingCartService.this.setShowSLMergeResult(true);
          ShoppingCartService.this.mBus.post(new LoginSyncResultEvent(ShoppingCartService.this.mSLMergeResult));
        }
      });
      return;
    }
    catch (Exception localException)
    {
      localException.printStackTrace();
    }
  }

  private void notifyLoginSyncFailed()
  {
    try
    {
      this.mHandler.post(new Runnable()
      {
        public void run()
        {
          User localUser = UserService.i(ShoppingCartService.this.mContext).getUser();
          if ((localUser != null) && (localUser.isLoggedIn()))
            ShoppingCartService.this.mBus.post(new LoginSyncFailedEvent());
        }
      });
      return;
    }
    catch (Exception localException)
    {
      localException.printStackTrace();
    }
  }

  private void notifySLSyncStart()
  {
    try
    {
      this.mHandler.post(new Runnable()
      {
        public void run()
        {
          ShoppingCartService.this.mBus.post(new StartSyncEvent());
        }
      });
      return;
    }
    catch (Exception localException)
    {
      localException.printStackTrace();
    }
  }

  private void notifySessionExpired(boolean paramBoolean)
  {
    reset();
    final String str = UserService.i(this.mContext).getUser().getEmailID();
    try
    {
      UserService.i(this.mContext).logout(paramBoolean);
      this.mHandler.post(new Runnable()
      {
        public void run()
        {
          String str = "";
          if ((str != null) && (!str.isEmpty()))
            str = str;
          ShoppingCartService.this.mBus.post(new SessionExpiredEvent(str));
        }
      });
      return;
    }
    catch (IOException localIOException)
    {
      while (true)
        localIOException.printStackTrace();
    }
  }

  private void notifySyncFailed()
  {
    try
    {
      this.mHandler.post(new Runnable()
      {
        public void run()
        {
          ShoppingCartService.this.mBus.post(new SyncFailedEvent());
        }
      });
      return;
    }
    catch (Exception localException)
    {
      localException.printStackTrace();
    }
  }

  private boolean processLoginSync(SyncEventModel paramSyncEventModel, PersistentQueue paramPersistentQueue)
  {
    ShoppingBags localShoppingBags = null;
    try
    {
      paramPersistentQueue.reset();
      startSyncSL();
      User localUser = UserService.i(this.mContext).getUser();
      StoreRef localStoreRef = AppConfigManager.i(this.mContext).getAppConfigData().getFavStore();
      String str1 = "";
      localShoppingBags = null;
      if (localStoreRef != null)
        str1 = localStoreRef.getStoreNo();
      localShoppingBags = syncSLWLSync(paramSyncEventModel, localUser, str1);
      if ((localShoppingBags != null) && (localShoppingBags.isSuccessful()) && (this.mLoginSyncInPocess))
        if ((localUser != null) && (!localUser.isLoggedIn()))
        {
          paramPersistentQueue.reset();
          bool1 = true;
        }
      while (true)
      {
        this.mLoginSyncInPocess = false;
        if ((localShoppingBags == null) || (!localShoppingBags.isSuccessful()))
        {
          notifyLoginSyncFailed();
          paramPersistentQueue.reset();
          paramPersistentQueue.push(paramSyncEventModel);
          bool1 = false;
          this.offlineItemList = getPostDataforSync(true);
        }
        if (bool1)
          paramPersistentQueue.pop();
        return bool1;
        String str2 = localShoppingBags.getBagId();
        bool1 = false;
        if (str2 != null)
        {
          List localList = localShoppingBags.getShoppingBagItemList(str2);
          this.mLoginSyncInPocess = false;
          updateShoppingList(localList, str2, true);
          notifyLoginSync(localShoppingBags);
          bool1 = true;
          continue;
          bool1 = false;
          if (localShoppingBags != null)
            if (localShoppingBags.getErrorCode() != 404)
            {
              boolean bool2 = localShoppingBags.isStatusCode(404);
              bool1 = false;
              if (!bool2);
            }
            else
            {
              paramPersistentQueue.reset();
              bool1 = true;
            }
        }
      }
    }
    catch (Exception localException)
    {
      while (true)
      {
        L.E(localException.getMessage());
        boolean bool1 = false;
      }
    }
  }

  private boolean processOtherSLEvent(SyncEventModel paramSyncEventModel, PersistentQueue paramPersistentQueue)
  {
    String str1 = paramSyncEventModel.getEvent();
    User localUser = UserService.i(this.mContext).getUser();
    StoreRef localStoreRef = AppConfigManager.i(this.mContext).getAppConfigData().getFavStore();
    String str2 = "";
    boolean bool1 = false;
    if (localStoreRef != null)
      str2 = localStoreRef.getStoreNo();
    if ((TextUtils.isEmpty(ShoppingCart.i(this.mContext).getShoppingBagId())) && (!str1.equals("event_sync")))
    {
      paramPersistentQueue.reset();
      return processSync(paramPersistentQueue);
    }
    if (localUser != null);
    while (true)
    {
      try
      {
        if (localUser.isLoggedIn())
        {
          boolean bool2 = str1.equals("event_add");
          bool1 = false;
          ShoppingBags localShoppingBags;
          if (bool2)
          {
            localShoppingBags = addItemWLSync(paramSyncEventModel, localUser, str2);
            bool1 = false;
            if (localShoppingBags != null)
            {
              boolean bool3 = localShoppingBags.isSuccessful();
              if (bool3)
              {
                bool1 = true;
                if (bool1)
                  paramPersistentQueue.pop();
                return bool1;
              }
            }
          }
          else
          {
            boolean bool5 = str1.equals("event_remove");
            bool1 = false;
            if (bool5)
            {
              localShoppingBags = removeItemWLSync(paramSyncEventModel, localUser, str2);
              continue;
            }
            boolean bool6 = str1.equals("event_update");
            localShoppingBags = null;
            bool1 = false;
            if (!bool6)
              continue;
            localShoppingBags = updateItemWLSync(paramSyncEventModel, localUser, str2);
            continue;
          }
          if (localShoppingBags.getErrorCode() != 404)
          {
            boolean bool4 = localShoppingBags.isStatusCode(404);
            bool1 = false;
            if (!bool4);
          }
          else
          {
            paramPersistentQueue.reset();
            notifySessionExpired(false);
            bool1 = true;
          }
          if ((localShoppingBags.getErrorCode() != 500) && (!localShoppingBags.isStatusCode(500)))
            continue;
          ResetBagID();
          continue;
        }
      }
      catch (Exception localException)
      {
        L.E(localException.getMessage());
        continue;
      }
      paramPersistentQueue.reset();
      bool1 = true;
    }
  }

  private boolean processSync(PersistentQueue paramPersistentQueue)
  {
    boolean bool1 = false;
    try
    {
      this.mSyncInPocess = true;
      localUser = UserService.i(this.mContext).getUser();
      StoreRef localStoreRef = AppConfigManager.i(this.mContext).getAppConfigData().getFavStore();
      str1 = "";
      bool1 = false;
      if (localStoreRef != null)
        str1 = localStoreRef.getStoreNo();
      bool1 = false;
      if ((localUser != null) && (localUser.isLoggedIn()))
      {
        long l2 = ShoppingCart.i(this.mContext).getLastSyncedTime();
        if (Math.abs(System.currentTimeMillis() - l2) >= 86400000L)
        {
          ShoppingBags localShoppingBags = getShoppingBagsWLSync(localUser, "", ShoppingCart.i(this.mContext).getShoppingBagId());
          bool1 = false;
          if ((localShoppingBags != null) && (localShoppingBags.isSuccessful()))
          {
            boolean bool4 = this.mSyncInPocess;
            bool1 = false;
            if (bool4)
            {
              String str2 = localShoppingBags.getBagId();
              bool1 = false;
              if (str2 != null)
              {
                List localList2 = localShoppingBags.getShoppingBagItemList(str2);
                updateStockInfo(localList2, str1);
                this.mSyncInPocess = false;
                updateShoppingList(localList2, str2, false);
                bool1 = true;
              }
            }
          }
          while (true)
          {
            if (bool1)
              paramPersistentQueue.pop();
            this.mSyncInPocess = false;
            return bool1;
            if (localShoppingBags.getErrorCode() != 404)
            {
              boolean bool3 = localShoppingBags.isStatusCode(404);
              bool1 = false;
              if (!bool3);
            }
            else
            {
              paramPersistentQueue.reset();
              notifySessionExpired(false);
              bool1 = true;
            }
            if ((localShoppingBags.getErrorCode() == 500) || (localShoppingBags.isStatusCode(500)))
              ResetBagID();
          }
        }
      }
    }
    catch (Exception localException)
    {
      while (true)
      {
        User localUser;
        String str1;
        L.E(localException.getMessage());
        continue;
        int j = isLoginSessionValid(localUser);
        if (j == 0)
        {
          setStockInfo(ShoppingCart.i(this.mContext).getProductList(), str1);
          bool1 = true;
        }
        else
        {
          bool1 = false;
          if (j == 1)
          {
            paramPersistentQueue.reset();
            notifySessionExpired(false);
            bool1 = true;
          }
          else
          {
            bool1 = true;
            notifySyncFailed();
            continue;
            long l1 = ShoppingCart.i(this.mContext).getLastSyncedTime();
            if (Math.abs(System.currentTimeMillis() - l1) >= 86400000L)
            {
              ProductListing localProductListing = getGuestShoppingBagsSync(str1);
              bool1 = false;
              if (localProductListing != null)
              {
                boolean bool2 = localProductListing.isSuccessful();
                bool1 = false;
                if (bool2)
                {
                  paramPersistentQueue.reset();
                  List localList1 = localProductListing.getRetailItemComm();
                  bool1 = false;
                  if (localList1 != null)
                  {
                    int i = updateGuestStockInfo(localProductListing.getRetailItemComm(), str1);
                    if (i != -1)
                    {
                      this.mSyncInPocess = false;
                      updateGuestShoppingList(localProductListing.getRetailItemComm(), false, i);
                      bool1 = true;
                    }
                    else
                    {
                      notifySyncFailed();
                      bool1 = false;
                    }
                  }
                }
              }
            }
            else
            {
              setStockInfo(ShoppingCart.i(this.mContext).getProductList(), str1);
              bool1 = true;
            }
          }
        }
      }
    }
  }

  private ShoppingBags removeItemWLSync(SyncEventModel paramSyncEventModel, User paramUser, String paramString)
    throws Exception
  {
    ShoppingBagSection localShoppingBagSection = createPostData(paramSyncEventModel.getItems());
    return invokeRequestWlResponseListener(RequestUtil.getDeleteItemRequestWL(this.mContext, paramUser.getSessionContext().getEmailAddress(), ShoppingCart.i(this.mContext).getShoppingBagId(), localShoppingBagSection, paramUser.getSessionKey()));
  }

  private void setStockInfo(Collection<RetailItemCommunication> paramCollection, String paramString)
  {
    int i = 1;
    int j = 0;
    boolean bool1 = paramCollection.isEmpty();
    boolean bool2 = false;
    int k = 0;
    Iterator localIterator;
    if (!bool1)
      localIterator = paramCollection.iterator();
    while (true)
    {
      RetailItemCommunication localRetailItemCommunication;
      if (localIterator.hasNext())
      {
        localRetailItemCommunication = (RetailItemCommunication)localIterator.next();
        if (localRetailItemCommunication != null)
        {
          ProductService.STOCK_STATUS localSTOCK_STATUS = ProductService.STOCK_STATUS.NONE;
          if ((localRetailItemCommunication.getStockAvailability() != null) && (localRetailItemCommunication.getStockAvailability().getStockAvailability() != null) && (!localRetailItemCommunication.getStockAvailability().getStockAvailability().isEmpty()))
          {
            RetailItemAvailability localRetailItemAvailability = ((StockAvailability)localRetailItemCommunication.getStockAvailability().getStockAvailability().get(0)).getRetailItemAvailability();
            localSTOCK_STATUS = ProductService.i(this.mContext).getStockStatus(localRetailItemAvailability);
          }
          StockAvailabilityResponse localStockAvailabilityResponse = ProductService.i(this.mContext).getProductStockInfo(paramString, localRetailItemCommunication);
          if ((localStockAvailabilityResponse == null) || (!localStockAvailabilityResponse.isSuccessful()) || (localStockAvailabilityResponse.getStockAvailability() == null) || (localStockAvailabilityResponse.getStockAvailability().isEmpty()))
            break label274;
          if (!ProductService.i(this.mContext).getStockStatus(((StockAvailability)localStockAvailabilityResponse.getStockAvailability().get(0)).getRetailItemAvailability()).equals(localSTOCK_STATUS))
          {
            localRetailItemCommunication.setStockAvailability(localStockAvailabilityResponse);
            bool2 = true;
            ShoppingCart.i(this.mContext).updateProductStockInfo(localRetailItemCommunication);
          }
        }
      }
      while (j > 2)
      {
        i = 0;
        if (i == 0)
          break label295;
        this.mSyncInPocess = false;
        ShoppingCart.i(this.mContext).updateCartAfterStockCheck(k, bool2);
        return;
        label274: j++;
      }
      if (isLoworOutOfStock(localRetailItemCommunication))
        k++;
    }
    label295: notifySyncFailed();
  }

  private void startSyncSL()
  {
    this.mLoginSyncInPocess = true;
    notifySLSyncStart();
  }

  private ShoppingBags syncSLWLSync(SyncEventModel paramSyncEventModel, User paramUser, String paramString)
    throws Exception
  {
    ShoppingBagSection localShoppingBagSection = createPostData(getPostDataforSync(true));
    return invokeRequestWlResponseListener(RequestUtil.getSyncSLRequestWL(this.mContext, paramUser.getSessionContext().getEmailAddress(), localShoppingBagSection, paramUser.getSessionKey()));
  }

  private void updateChildCollectedState(RetailItemCommunication paramRetailItemCommunication1, RetailItemCommunication paramRetailItemCommunication2)
  {
    if ((paramRetailItemCommunication1 != null) && (paramRetailItemCommunication1.getRetailItemCommChildList() != null) && (paramRetailItemCommunication1.getRetailItemCommChildList().getRetailItemCommChild() != null) && (paramRetailItemCommunication1.getRetailItemCommChildList().getRetailItemCommChild().size() > 0))
    {
      Iterator localIterator = paramRetailItemCommunication1.getRetailItemCommChildList().getRetailItemCommChild().iterator();
      while (localIterator.hasNext())
      {
        RetailItemCommChild localRetailItemCommChild = (RetailItemCommChild)localIterator.next();
        localRetailItemCommChild.setCollected(isChildCollected(localRetailItemCommChild.getItemNo(), paramRetailItemCommunication2));
      }
    }
  }

  private void updateChildCollectedState(RetailItemCommunication paramRetailItemCommunication, boolean paramBoolean)
  {
    if ((paramRetailItemCommunication != null) && (paramRetailItemCommunication.getRetailItemCommChildList() != null) && (paramRetailItemCommunication.getRetailItemCommChildList().getRetailItemCommChild() != null) && (paramRetailItemCommunication.getRetailItemCommChildList().getRetailItemCommChild().size() > 0))
    {
      Iterator localIterator = paramRetailItemCommunication.getRetailItemCommChildList().getRetailItemCommChild().iterator();
      while (localIterator.hasNext())
        ((RetailItemCommChild)localIterator.next()).setCollected(paramBoolean);
    }
  }

  private void updateGuestShoppingList(Collection<RetailItemCommunication> paramCollection, boolean paramBoolean, int paramInt)
  {
    if (paramCollection != null)
    {
      Collection localCollection = ShoppingCart.i(this.mContext).getProductList();
      ArrayList localArrayList = new ArrayList();
      if (!paramCollection.isEmpty())
      {
        Iterator localIterator = paramCollection.iterator();
        while (localIterator.hasNext())
        {
          RetailItemCommunication localRetailItemCommunication = (RetailItemCommunication)localIterator.next();
          if (localRetailItemCommunication != null)
          {
            Quantity localQuantity = getQuantity(localRetailItemCommunication.getItemNo(), localCollection);
            if (localQuantity != null)
            {
              localRetailItemCommunication.setQuantity(localQuantity);
              localArrayList.add(localRetailItemCommunication);
              localRetailItemCommunication.setCollected(isCollected(localRetailItemCommunication.getItemNo(), localCollection));
              updateChildCollectedState(localRetailItemCommunication, getLocalItem(localRetailItemCommunication.getItemNo(), localCollection));
            }
          }
        }
      }
      updateProductWithNotification(localArrayList, localCollection, paramInt, "", false, false);
    }
  }

  private int updateGuestStockInfo(Collection<RetailItemCommunication> paramCollection, String paramString)
  {
    boolean bool = paramCollection.isEmpty();
    int i = 0;
    if (!bool)
    {
      int j = 0;
      Iterator localIterator = paramCollection.iterator();
      while (localIterator.hasNext())
      {
        RetailItemCommunication localRetailItemCommunication = (RetailItemCommunication)localIterator.next();
        if (localRetailItemCommunication != null)
        {
          StockAvailabilityResponse localStockAvailabilityResponse = ProductService.i(this.mContext).getProductStockInfo(paramString, localRetailItemCommunication);
          if ((localStockAvailabilityResponse == null) || (!localStockAvailabilityResponse.isSuccessful()) || (localStockAvailabilityResponse.getStockAvailability() == null) || (localStockAvailabilityResponse.getStockAvailability().isEmpty()))
            break label116;
          localRetailItemCommunication.setStockAvailability(localStockAvailabilityResponse);
        }
        while (j > 2)
        {
          return -1;
          label116: j++;
        }
        if (isLoworOutOfStock(localRetailItemCommunication))
          i++;
      }
    }
    return i;
  }

  private ShoppingBags updateItemWLSync(SyncEventModel paramSyncEventModel, User paramUser, String paramString)
    throws Exception
  {
    ShoppingBagSection localShoppingBagSection = createPostData(paramSyncEventModel.getItems());
    return invokeRequestWlResponseListener(RequestUtil.getUpdateItemRequestWL(this.mContext, paramUser.getSessionContext().getEmailAddress(), ShoppingCart.i(this.mContext).getShoppingBagId(), localShoppingBagSection, paramUser.getSessionKey()));
  }

  private void updateProductWithNotification(List<RetailItemCommunication> paramList, Collection<RetailItemCommunication> paramCollection, int paramInt, String paramString, boolean paramBoolean1, boolean paramBoolean2)
  {
    int i = 0;
    int j = 0;
    if (paramCollection != null)
    {
      Iterator localIterator = paramCollection.iterator();
      while (localIterator.hasNext())
      {
        RetailItemCommunication localRetailItemCommunication1 = (RetailItemCommunication)localIterator.next();
        RetailItemCommunication localRetailItemCommunication2 = GetEquivalentNewItem(localRetailItemCommunication1, paramList);
        if (localRetailItemCommunication2 != null)
        {
          if (isPriceUpdated(localRetailItemCommunication1, localRetailItemCommunication2))
            i++;
        }
        else
          j++;
      }
    }
    if (paramList != null)
    {
      if (paramBoolean2)
      {
        i = 0;
        j = 0;
      }
      ShoppingCart.i(this.mContext).updateCartAfterSync(paramList, System.currentTimeMillis(), paramInt, i, j, paramString, paramBoolean1, paramBoolean2);
    }
    Constant.i().setProductModified(true);
  }

  private void updateStockInfo(List<ShoppingBagItem> paramList, String paramString)
  {
    int i;
    Iterator localIterator;
    if (!paramList.isEmpty())
    {
      i = 0;
      localIterator = paramList.iterator();
    }
    while (true)
    {
      if (localIterator.hasNext())
      {
        RetailItemCommunication localRetailItemCommunication = ((ShoppingBagItem)localIterator.next()).getRetailItemCommunications();
        if (localRetailItemCommunication != null)
        {
          StockAvailabilityResponse localStockAvailabilityResponse = ProductService.i(this.mContext).getProductStockInfo(paramString, localRetailItemCommunication);
          if ((localStockAvailabilityResponse == null) || (!localStockAvailabilityResponse.isSuccessful()) || (localStockAvailabilityResponse.getStockAvailability() == null) || (localStockAvailabilityResponse.getStockAvailability().isEmpty()))
            break label111;
          localRetailItemCommunication.setStockAvailability(localStockAvailabilityResponse);
        }
      }
      while (i > 2)
      {
        return;
        label111: i++;
      }
    }
  }

  public boolean getLoginSyncInProcess()
  {
    return this.mLoginSyncInPocess;
  }

  public List<ShoppingBagItem> getPostDataforSync(boolean paramBoolean)
  {
    Collection localCollection = ShoppingCart.i(this.mContext).getProductList();
    ArrayList localArrayList = new ArrayList();
    if ((localCollection != null) && (!localCollection.isEmpty()))
    {
      Iterator localIterator = localCollection.iterator();
      while (localIterator.hasNext())
      {
        RetailItemCommunication localRetailItemCommunication = (RetailItemCommunication)localIterator.next();
        Quantity localQuantity = localRetailItemCommunication.getQuantity();
        String str = "1";
        if (localQuantity != null)
          str = localQuantity.getQuantity();
        ShoppingBagItem localShoppingBagItem = new ShoppingBagItem(localRetailItemCommunication.getItemNo(), str, localRetailItemCommunication.getItemType());
        if (!this.offlineItemList.contains(localShoppingBagItem))
          localArrayList.add(localShoppingBagItem);
      }
    }
    return localArrayList;
  }

  public boolean getSLSyncInProcess()
  {
    return (this.mSyncInPocess) || (this.mLoginSyncInPocess);
  }

  public void getShoppingBagByIdWLAsyncWL(final ServiceCallback<ShoppingBags> paramServiceCallback, final User paramUser, String paramString1, final String paramString2)
  {
    this.mExecutorService.execute(new Runnable()
    {
      public void run()
      {
        try
        {
          WLRequest localWLRequest = RequestUtil.getShoppingBagRequestWL(ShoppingCartService.this.mContext, paramUser.getSessionContext().getEmailAddress(), paramString2, paramUser.getSessionKey());
          WLEngine.GenericInvokeRequestWlResponseListener local1 = new WLEngine.GenericInvokeRequestWlResponseListener(paramServiceCallback, ShoppingBags.class)
          {
            public void onFailure(WLFailResponse paramAnonymous2WLFailResponse)
            {
              Log.d("KOMPIS", "WL call fail " + paramAnonymous2WLFailResponse.getStatus());
              this.mResponse = super.parseResponse(paramAnonymous2WLFailResponse);
              if (this.mCallback != null)
                this.mCallback.callbackDone(this.mResponse, null, null);
            }

            public void onSuccess(WLResponse paramAnonymous2WLResponse)
            {
              super.onSuccess(paramAnonymous2WLResponse);
            }
          };
          if (WLEngine.i(ShoppingCartService.this.mContext).invoke(localWLRequest, local1))
            return;
          paramServiceCallback.callbackDone(null, null, new WLEngine.WlException());
          return;
        }
        catch (Exception localException)
        {
          localException.printStackTrace();
          paramServiceCallback.callbackDone(null, null, localException);
        }
      }
    });
  }

  public boolean getSyncInProcess()
  {
    return this.mSyncInPocess;
  }

  public String getmSLMergeResult()
  {
    return this.mSLMergeResult;
  }

  public boolean isShowSLMergeResult()
  {
    return this.showSLMergeResult;
  }

  public boolean isSyncCompleted()
  {
    int i = this.mQueue.size();
    if (i > 1);
    SyncEventModel localSyncEventModel;
    do
    {
      return false;
      if (i != 1)
        break;
      localSyncEventModel = this.mQueue.peak();
    }
    while ((localSyncEventModel != null) && ((localSyncEventModel.getEvent().equals("event_add")) || (localSyncEventModel.getEvent().equals("event_remove")) || (localSyncEventModel.getEvent().equals("event_update"))));
    return true;
  }

  public void mergeShoppingList(List<ShoppingBagItem> paramList, String paramString)
  {
    if (paramList != null)
    {
      Collection localCollection = ShoppingCart.i(this.mContext).getProductList();
      ArrayList localArrayList1 = new ArrayList();
      boolean bool = paramList.isEmpty();
      int i = 0;
      if (!bool)
      {
        ArrayList localArrayList2 = new ArrayList();
        Iterator localIterator1 = paramList.iterator();
        while (localIterator1.hasNext())
        {
          ShoppingBagItem localShoppingBagItem = (ShoppingBagItem)localIterator1.next();
          RetailItemCommunication localRetailItemCommunication2 = localShoppingBagItem.getRetailItemCommunications();
          if (localRetailItemCommunication2 != null)
          {
            int j = getLocalQuantity(localRetailItemCommunication2.getItemNo(), localCollection);
            int k = (int)(Float.parseFloat(localShoppingBagItem.getItemQty()) + j);
            localRetailItemCommunication2.setQuantity(new Quantity(localRetailItemCommunication2.getItemUnitCode(), String.valueOf(k)));
            if (j > 0)
              localArrayList2.add(new ShoppingBagItem(localRetailItemCommunication2.getItemNo(), String.valueOf(k), localRetailItemCommunication2.getItemType()));
            localArrayList1.add(localRetailItemCommunication2);
            if (isLoworOutOfStock(localRetailItemCommunication2))
              i++;
            if ((j == 0) || (k != j))
            {
              localRetailItemCommunication2.setCollected(false);
              updateChildCollectedState(localRetailItemCommunication2, false);
            }
            else
            {
              localRetailItemCommunication2.setCollected(isCollected(localRetailItemCommunication2.getItemNo(), localCollection));
              updateChildCollectedState(localRetailItemCommunication2, getLocalItem(localRetailItemCommunication2.getItemNo(), localCollection));
            }
          }
        }
        if (!localArrayList2.isEmpty())
          processSyncSL(new SyncEventModel(localArrayList2, "event_update"));
      }
      ArrayList localArrayList3 = new ArrayList();
      Iterator localIterator2 = localCollection.iterator();
      while (localIterator2.hasNext())
      {
        RetailItemCommunication localRetailItemCommunication1 = (RetailItemCommunication)localIterator2.next();
        if (isNotPresentinItems(localRetailItemCommunication1, localArrayList1))
        {
          localArrayList1.add(localRetailItemCommunication1);
          localArrayList3.add(new ShoppingBagItem(localRetailItemCommunication1.getItemNo(), localRetailItemCommunication1.getQuantity().getQuantity(), localRetailItemCommunication1.getItemType()));
        }
      }
      if (!localArrayList3.isEmpty())
        processSyncSL(new SyncEventModel(localArrayList3, "event_add"));
      updateProductWithNotification(localArrayList1, localCollection, i, paramString, true, false);
    }
  }

  void notifyShoppingList(final boolean paramBoolean)
  {
    this.mSyncInPocess = false;
    this.mLoginSyncInPocess = false;
    this.mHandler.post(new Runnable()
    {
      public void run()
      {
        ShoppingCartService.this.mBus.post(new ShoppingListRefreshEvent(paramBoolean));
      }
    });
  }

  public boolean processEventQueue(PersistentQueue paramPersistentQueue)
  {
    SyncEventModel localSyncEventModel = paramPersistentQueue.peak();
    String str = localSyncEventModel.getEvent();
    if (str.equalsIgnoreCase("event_login_sync"))
      return processLoginSync(localSyncEventModel, paramPersistentQueue);
    if (str.equalsIgnoreCase("event_sync"))
      return processSync(paramPersistentQueue);
    return processOtherSLEvent(localSyncEventModel, paramPersistentQueue);
  }

  public void processSyncSL(SyncEventModel paramSyncEventModel)
  {
    if (paramSyncEventModel != null)
    {
      if (!paramSyncEventModel.getEvent().equals("event_clear"))
        break label49;
      this.mQueue.reset();
    }
    while (true)
    {
      L.D(this, "sync service request for event processing. with data " + paramSyncEventModel);
      return;
      label49: if (paramSyncEventModel != null)
      {
        this.mQueue.push(paramSyncEventModel);
        startProcessingIfRequired();
      }
    }
  }

  public boolean refreshSL()
  {
    if ((getLoginSyncInProcess()) || (getSyncInProcess()))
      return false;
    processSyncSL(new SyncEventModel());
    return true;
  }

  public void reset()
  {
    this.mSyncInPocess = false;
    this.mLoginSyncInPocess = false;
    this.showSLMergeResult = false;
    this.mSLMergeResult = "";
  }

  public void setSLMergeResult(String paramString)
  {
    this.mSLMergeResult = paramString;
  }

  public void setShowSLMergeResult(boolean paramBoolean)
  {
    this.showSLMergeResult = paramBoolean;
    if (!paramBoolean)
      this.mSLMergeResult = "";
  }

  public void startLoginSyncService()
  {
    processSyncSL(new SyncEventModel(i(this.mContext).getPostDataforSync(false), "event_login_sync"));
  }

  public void startProcessingIfRequired()
  {
    L.D(this, "Lets start the sync service background thread ");
    if ((this.mFuture == null) || (this.mFuture.isDone()))
      this.mFuture = this.mExecutorService.submit(new Callable()
      {
        public Boolean call()
          throws Exception
        {
          ShoppingCartService.this.loadEventQueueIfRequired();
          L.D(this, "pending event in event queue are " + ShoppingCartService.this.mQueue.size());
          int i = 0;
          while ((!ShoppingCartService.this.mQueue.isEmpty()) && (i <= 0))
          {
            if (!ShoppingCartService.this.processEventQueue(ShoppingCartService.this.mQueue))
              i++;
            try
            {
              Thread.sleep(100L);
            }
            catch (Exception localException)
            {
              localException.printStackTrace();
            }
          }
          ShoppingCartService.access$202(ShoppingCartService.this, null);
          ShoppingCartService.this.notifyShoppingList(ShoppingCartService.this.mQueue.isEmpty());
          System.gc();
          return Boolean.valueOf(true);
        }
      });
  }

  public void updateShoppingList(List<ShoppingBagItem> paramList, String paramString, boolean paramBoolean)
  {
    if (paramList != null)
    {
      Collection localCollection = ShoppingCart.i(this.mContext).getProductList();
      ArrayList localArrayList = new ArrayList();
      boolean bool = paramList.isEmpty();
      int i = 0;
      if (!bool)
      {
        Iterator localIterator = paramList.iterator();
        while (localIterator.hasNext())
        {
          ShoppingBagItem localShoppingBagItem = (ShoppingBagItem)localIterator.next();
          if (this.offlineItemList.contains(localShoppingBagItem))
            this.offlineItemList.remove(localShoppingBagItem);
          RetailItemCommunication localRetailItemCommunication = localShoppingBagItem.getRetailItemCommunications();
          if (localRetailItemCommunication != null)
          {
            localRetailItemCommunication.setQuantity(new Quantity(localRetailItemCommunication.getItemUnitCode(), localShoppingBagItem.getItemQty()));
            localArrayList.add(localRetailItemCommunication);
            localRetailItemCommunication.setCollected(isCollected(localRetailItemCommunication.getItemNo(), localCollection));
            if (isLoworOutOfStock(localRetailItemCommunication))
              i++;
            int j = getLocalQuantity(localRetailItemCommunication.getItemNo(), localCollection);
            int k = (int)Float.parseFloat(localShoppingBagItem.getItemQty());
            if ((j == 0) || (k != j))
            {
              localRetailItemCommunication.setCollected(false);
              updateChildCollectedState(localRetailItemCommunication, false);
            }
            else
            {
              localRetailItemCommunication.setCollected(isCollected(localRetailItemCommunication.getItemNo(), localCollection));
              updateChildCollectedState(localRetailItemCommunication, getLocalItem(localRetailItemCommunication.getItemNo(), localCollection));
            }
          }
        }
        if (!this.offlineItemList.isEmpty())
        {
          processSyncSL(new SyncEventModel(this.offlineItemList, "event_update"));
          this.offlineItemList.clear();
        }
      }
      updateProductWithNotification(localArrayList, localCollection, i, paramString, true, paramBoolean);
    }
  }
}

/* Location:           C:\Documents and Settings\Cesar Cabello Cea\Mis documentos\Downloads\apk-downloader\com.ikea.kompis-6_dex2jar.jar
 * Qualified Name:     com.ikea.shared.shopping.service.ShoppingCartService
 * JD-Core Version:    0.6.2
 */