/*
 * #%L
 * Bitrepository Alarm Service
 * 
 * $Id$
 * $HeadURL$
 * %%
 * Copyright (C) 2010 - 2012 The State and University Library, The Royal Library and The State Archives, Denmark
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as 
 * published by the Free Software Foundation, either version 2.1 of the 
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Lesser Public License for more details.
 * 
 * You should have received a copy of the GNU General Lesser Public 
 * License along with this program.  If not, see
 * <http://www.gnu.org/licenses/lgpl-2.1.html>.
 * #L%
 */
package org.bitrepository.alarm.alarmservice;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;

import org.bitrepository.alarm.AlarmService;
import org.bitrepository.alarm.AlarmServiceFactory;
import org.bitrepository.bitrepositoryelements.Alarm;
import org.bitrepository.bitrepositoryelements.AlarmCode;
import org.bitrepository.common.utils.CalendarUtils;
import org.bitrepository.common.utils.TimeUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Path("/AlarmService")
public class RestAlarmService {
    private Logger log = LoggerFactory.getLogger(getClass());

	private AlarmService alarmService;
    
    public RestAlarmService() {
        alarmService = AlarmServiceFactory.getAlarmService();
    }
    
    /**
     * getShortAlarmList exposes the possibility of getting the list of the most recent alarms  
     * @return A string containing the data of the last alarms. 
     */
    @GET
    @Path("/getShortAlarmList/")
    @Produces("application/json")
    public List<Alarm> getShortAlarmList() {
        List<Alarm> alarmList = new ArrayList<Alarm>();
        alarmList.addAll(alarmService.extractAlarms(null, null, null, null, null, null, 10, false));
        return alarmList;
    }
    
    /**
     * getFullAlarmList exposes the possibility of getting the list of all alarms received   
     * @return A string containing the data of all alarms received. 
     */
    @GET
    @Path("/getFullAlarmList/")
    @Produces("application/json")
    public List<Alarm> getFullAlarmList() {
        List<Alarm> alarmList = new ArrayList<Alarm>();
        alarmList.addAll(alarmService.extractAlarms(null, null, null, null, null, null, null, true));
        return alarmList;
    }
       
    @POST
    @Path("/queryAlarms/")
    @Consumes("application/x-www-form-urlencoded")
    @Produces("application/json")
    public String queryAlarms(
            @FormParam("fromDate") String fromDate,
            @FormParam("toDate") String toDate,
            @FormParam("fileID") String fileID,
            @FormParam("reportingComponent") String reportingComponent,
            @FormParam("alarmCode") String alarmCode,
            @FormParam("collectionID") String collectionID,
            @DefaultValue("10") @FormParam("maxAlarms") Integer maxAlarms,
            @DefaultValue("true") @FormParam ("oldestAlarmFirst") boolean oldestAlarmFirst) {
        JSONArray array = new JSONArray();
        Date from = makeDateObject(fromDate);
        Date to = makeDateObject(toDate);
        
        Collection<Alarm> alarms = alarmService.extractAlarms(contentOrNull(reportingComponent), makeAlarmCode(alarmCode), 
                from, to, contentOrNull(fileID), makeCollectionID(collectionID), maxAlarms, oldestAlarmFirst);
        
        if(alarms != null) {
            for(Alarm alarm : alarms) {
                array.put(makeJSONEntry(alarm));
            }
        }    
        return array.toString();
    }
    
    @POST
    @Path("/queryAlarms/")
    @Consumes("application/json")
    @Produces("application/json")
    public String queryAlarms(AlarmServiceInput input) {
        JSONArray array = new JSONArray();
        Date from = makeDateObject(input.getFromDate());
        Date to = makeDateObject(input.getToDate());
       
        Collection<Alarm> alarms = alarmService.extractAlarms(contentOrNull(input.getReportingComponent()), makeAlarmCode(input.getAlarmCode()),
                from, to, contentOrNull(input.getFileID()), makeCollectionID(input.getCollectionID()), input.getMaxAlarms(), input.isOldestAlarmsFirst());
       
        if(alarms != null) {
            for(Alarm alarm : alarms) {
                array.put(makeJSONEntry(alarm));
            }
        }   
        return array.toString();
    }
    
    private Date makeDateObject(String dateStr) {
        if(dateStr == null || dateStr.trim().isEmpty()) {
            return null;
        } else {
            String[] components = dateStr.split("/");
            int year = Integer.parseInt(components[2]);
            int month = Integer.parseInt(components[0]);
            int day = Integer.parseInt(components[1]);
            Calendar time = Calendar.getInstance();
            time.set(year, (month - 1), day);
            
            return time.getTime();
        }
    }
    
    private String makeCollectionID(String collectionID) {
        if(collectionID.equals("ALL")) {
           return null;
        } else {
            return collectionID;
        }
    }
    
    private AlarmCode makeAlarmCode(String alarmCodeStr) {
        if(alarmCodeStr.equals("ALL")) {
            return null;
        } else {
            return AlarmCode.fromValue(alarmCodeStr);
        }
    } 
    
    private String contentOrNull(String input) {
        if(input != null && input.trim().isEmpty()) {
            return null;
        } else {
            return input.trim();
        }
    }
    
    private JSONObject makeJSONEntry(Alarm alarm) {
        JSONObject obj = new JSONObject();
        try {
            obj.put("OrigDateTime", TimeUtils.shortDate(
                    CalendarUtils.convertFromXMLGregorianCalendar(alarm.getOrigDateTime())));
            obj.put("AlarmRaiser", alarm.getAlarmRaiser());
            obj.put("AlarmCode", alarm.getAlarmCode());
            obj.put("AlarmText", alarm.getAlarmText());
            return obj;
        } catch (JSONException e) {
            return (JSONObject) JSONObject.NULL;
        }
    } 
}

@@ -4305,38 +4305,43 @@
 on%22)%0A    public 
-String
+List%3CAlarm%3E
  queryAlarms(Ala
@@ -4368,51 +4368,8 @@
 ) %7B%0A
-        JSONArray array = new JSONArray();%0A
     
@@ -4802,115 +4802,42 @@
     
-if(alarms != null) %7B%0A            for(Alarm alarm : alarms) %7B%0A                array.put(makeJSONEntry
+return new ArrayList%3CAlarm%3E
 (alarm
-)
+s
 );%0A 
@@ -4847,59 +4847,8 @@
     
-    %7D%0A        %7D   %0A        return array.toString();
 %0A   

Output raw alarm objects as json in new service call