/*
 * Copyright (c) 2017, University of Oslo
 *
 * 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 HISP project 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 OWNER 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.
 */
package org.hisp.dhis.android.core.trackedentity;

import org.hisp.dhis.android.core.common.GenericCallData;
import org.hisp.dhis.android.core.common.IdentifiableObjectStore;
import org.hisp.dhis.android.core.common.ObjectWithoutUidStore;
import org.hisp.dhis.android.core.data.database.DatabaseAdapter;
import org.hisp.dhis.android.core.organisationunit.OrganisationUnitModel;
import org.hisp.dhis.android.core.organisationunit.OrganisationUnitStore;
import org.hisp.dhis.android.core.systeminfo.SystemInfo;
import org.hisp.dhis.android.core.systeminfo.SystemInfoCall;

import java.util.List;

import retrofit2.Response;
import retrofit2.Retrofit;

public final class TrackedEntityAttributeReservedValueManager {

    private final ObjectWithoutUidStore<TrackedEntityAttributeReservedValueModel> store;
    private final IdentifiableObjectStore<OrganisationUnitModel> organisationUnitStore;
    private final DatabaseAdapter databaseAdapter;
    private final Retrofit retrofit;

    private TrackedEntityAttributeReservedValueManager(DatabaseAdapter databaseAdapter, Retrofit retrofit) {
        this.databaseAdapter = databaseAdapter;
        this.retrofit = retrofit;
        this.store = TrackedEntityAttributeReservedValueStore.create(databaseAdapter);
        this.organisationUnitStore = OrganisationUnitStore.create(databaseAdapter);
    }

    public String getValue(String attribute, String organisationUnitUid) throws RuntimeException {
        deleteExpiredDates(attribute, organisationUnitUid);

        try {
            syncReservedValues(attribute, organisationUnitUid);
        } catch (Exception e) {
            throw new RuntimeException("Synchronization was not successful.", e);
        }

        List<TrackedEntityAttributeReservedValueModel> reservedValues = getReservedValues(attribute,
                organisationUnitUid);
        TrackedEntityAttributeReservedValueModel reservedValue = null;

        try {
            reservedValue = reservedValues.iterator().next();
        } catch (Exception e) {
            throw new RuntimeException("There are no reserved values.", e);
        }

        deleteReservedValue(reservedValue);

        return reservedValue.value();
    }

    List<TrackedEntityAttributeReservedValueModel> getReservedValues(String attributeUid, String orgUnitUid) {
        return this.store.selectWhere(TrackedEntityAttributeReservedValueModel.factory, attributeUid, orgUnitUid);
    }

    private void deleteReservedValue(TrackedEntityAttributeReservedValueModel reservedValueModel) {
        store.deleteWhere(reservedValueModel);
    }

    private void syncReservedValues(String attribute, String organisationUnitUid) throws Exception {
        List<TrackedEntityAttributeReservedValueModel> reservedValues = getReservedValues(attribute,
                organisationUnitUid);
        if (reservedValues.size() <= 50) {
            fillReservedValues(attribute, organisationUnitUid, reservedValues.size());
        }
    }

    private void deleteExpiredDates(String attributeUid, String orgUnitUid) {
        List<TrackedEntityAttributeReservedValueModel> reservedValues = getReservedValues(attributeUid, orgUnitUid);

        for (TrackedEntityAttributeReservedValueModel reservedValue : reservedValues) {
            if (reservedValue.expiryDate().getTime() < System.currentTimeMillis()) {
                deleteReservedValue(reservedValue);
            }
        }
    }

    private void fillReservedValues(String attribute, String organisationUnitUid, Integer size) throws Exception {
        Response systemInfoResponse = SystemInfoCall.FACTORY.create(databaseAdapter, retrofit).call();
        if (!systemInfoResponse.isSuccessful()) {
            throw new RuntimeException("SystemInfo call failed.");
        }

        SystemInfo systemInfo = (SystemInfo) systemInfoResponse.body();
        GenericCallData genericCallData = GenericCallData.create(databaseAdapter, retrofit,
                systemInfo.serverDate());

        Integer numberToReserve = 100 - size;
        OrganisationUnitModel organisationUnitModel =
                this.organisationUnitStore.selectByUid(organisationUnitUid, OrganisationUnitModel.factory);

        Response reservedValueResponse = TrackedEntityAttributeReservedValueEndpointCall.FACTORY.create(
                genericCallData, attribute, numberToReserve, organisationUnitModel).call();
        if (!reservedValueResponse.isSuccessful()) {
            throw new RuntimeException("New reserved values call failed.");
        }
    }

    public static TrackedEntityAttributeReservedValueManager create(DatabaseAdapter databaseAdapter,
                                                                    Retrofit retrofit) {
        return new TrackedEntityAttributeReservedValueManager(databaseAdapter, retrofit);
    }
}
@@ -2140,16 +2140,75 @@
 .List;%0A%0A
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;%0A
 import r
@@ -2946,32 +2946,120 @@
 dapter);%0A    %7D%0A%0A
+    @SuppressFBWarnings(%22DE_MIGHT_IGNORE%22)%0A    @SuppressWarnings(%22PMD.EmptyCatchBlock%22)%0A
     public Strin
@@ -3145,69 +3145,8 @@
 n %7B%0A
-        deleteExpiredDates(attribute, organisationUnitUid);%0A%0A
     
@@ -3267,36 +3267,11 @@
     
-throw new RuntimeException(%22
+// 
 Sync
@@ -3301,22 +3301,16 @@
 cessful.
-%22, e);
 %0A       
@@ -3452,24 +3452,25 @@
 itUid);%0A
+%0A
         
 TrackedE
@@ -3465,113 +3465,92 @@
     
-TrackedEntityAttributeReservedValueModel reservedValue = null;%0A%0A        try %7B%0A            reservedValue =
+if (reservedValues.isEmpty()) %7B%0A            throw new RuntimeException(%22There are no
  res
@@ -3558,153 +3558,133 @@
 rved
-V
+ v
 alues.
-iterator().next();%0A        %7D catch (Exception e) %7B%0A            throw new RuntimeException(%22There are no reserved v
+%22);%0A        %7D else %7B%0A            TrackedEntityAttributeReservedValueModel reservedValue = reservedV
 alues.
-%22, e
+get(0
 );%0A    
-    %7D%0A%0A
     
@@ -3723,17 +3723,20 @@
 Value);%0A
-%0A
+    
         
@@ -3761,24 +3761,34 @@
 ue.value();%0A
+        %7D%0A
     %7D%0A%0A    L
@@ -4262,32 +4262,92 @@
 ows Exception %7B%0A
+        deleteExpiredDates(attribute, organisationUnitUid);%0A
         List%3CTra

improve manager behavior