package com.agilex.healthcare.schedulingmanager.dataservice;

import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import agilex.commons.pagination.PaginationDataLayer;

import com.agilex.healthcare.schedulingmanager.datalayer.SchedulingDataLayer;
import com.agilex.healthcare.schedulingmanager.domain.WaitListEntries;
import com.agilex.healthcare.schedulingmanager.translator.WaitListTranslator;
import com.agilex.healthcare.schedulingmanager.utils.ListType;
import com.mongodb.DBObject;


/**
 * Created with IntelliJ IDEA.
 * User: patelh
 * Date: 12/11/13
 * Time: 1:06 PM
 * To change this template use File | Settings | File Templates.
 */
@Component
public class WaitListDataService {

    //private final Log LOGGER = LogFactory.getLog(WaitListDataService.class);

    private long    LIST_DATA_IS_STALE_AFTER = 180000;    // 3 minutes

    @Resource(name="paginationDataLayer")
    PaginationDataLayer       paginationDataLayer;

    public WaitListEntries getListForFacility(SchedulingDataLayer lvSchedulingDataLayer, boolean freshStart,
                                             String facilityCode, ListType                  waitlistType,
                                             HashMap<String, Boolean> sortFields, String    filter,
                                             int  firstRecord, int  lastRecord){
        WaitListEntries         waitListEntries = new WaitListEntries();
        WaitListTranslator      translator = new WaitListTranslator();
        Iterator<?>                waitListEntriesIterator;


        if((freshStart && listDataIsStale(facilityCode, waitlistType))
                || listDataIsStale(facilityCode, waitlistType)){
            WaitListEntries       ewlWaitListEntries = lvSchedulingDataLayer.getWaitListForFacility(facilityCode, waitlistType.getName());

            paginationDataLayer.saveList(translator.convertToDBObjects(ewlWaitListEntries), waitlistType.getName(), facilityCode, null, null, null, false);
        }

        waitListEntriesIterator = paginationDataLayer.getList(waitlistType.getName(), facilityCode, null, null, null, sortFields,
                                                          firstRecord, lastRecord, filter).iterator();
        while(waitListEntriesIterator.hasNext()) {
            DBObject dbObject = (DBObject)waitListEntriesIterator.next();

            waitListEntries.add(translator.convertFromDbObject(dbObject));
        }

        return waitListEntries;
    }

    private boolean listDataIsStale(String facilityCode, ListType waitlistType) {
        Date    lastPullTime;

        lastPullTime = paginationDataLayer.getLastPullTime(waitlistType.getName(), facilityCode, null, null, null);

        if(new Date().getTime() - lastPullTime.getTime() < LIST_DATA_IS_STALE_AFTER) {
            return false;
        }
        else {
            return true;
        }
    }

}
