//
//   Copyright 2016  Cityzen Data
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
//

package io.warp10.script.functions;

import io.warp10.continuum.store.Constants;
import io.warp10.script.NamedWarpScriptFunction;
import io.warp10.script.WarpScriptStackFunction;
import io.warp10.script.WarpScriptException;
import io.warp10.script.WarpScriptStack;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;

/**
 * Pushes on the stack the various elements of a timestamp for a given timezone
 */
public class TSELEMENTS extends NamedWarpScriptFunction implements WarpScriptStackFunction {
  
  private static final int MAX_TZ_CACHE_ENTRIES = 64;
  
  private final Map<String,DateTimeZone> tzones = new LinkedHashMap<String, DateTimeZone>() {
    protected boolean removeEldestEntry(java.util.Map.Entry<String, DateTimeZone> eldest) { return size() > MAX_TZ_CACHE_ENTRIES; };
  };
  
  public TSELEMENTS(String name) {
    super(name);
  }
  
  @Override
  public Object apply(WarpScriptStack stack) throws WarpScriptException {
    
    Object obj = stack.peek();
    
    String tz = null;
    
    if (obj instanceof String) {
      tz = (String) obj;
      stack.pop();
    } else if (!(obj instanceof Long)) {
      throw new WarpScriptException(getName() + " operates on a timestamp or a timestamp + timezone.");
    }

    DateTimeZone dtz = this.tzones.get(tz);
    
    if (null == dtz) {
      dtz = DateTimeZone.forID(null == tz ? "UTC" : tz);
      this.tzones.put(tz, dtz);
    }
    
    obj = stack.pop();
        
    if (!(obj instanceof Long)) {
      throw new WarpScriptException(getName() + " operates on a timestamp or a timestamp + timezone.");
    }
    
    long ts = (long) obj;
        
    // Convert ts to milliseconds
    
    long tsms = ts / Constants.TIME_UNITS_PER_MS;
    
    DateTime dt = new DateTime(tsms, dtz);

    // Extract components into an array
    
    List<Long> elements = new ArrayList<Long>();
    
    elements.add((long) dt.getYear());
    elements.add((long) dt.getMonthOfYear());
    elements.add((long) dt.getDayOfMonth());
    elements.add((long) dt.getHourOfDay());
    elements.add((long) dt.getMinuteOfHour());
    elements.add((long) dt.getSecondOfMinute());
    elements.add(ts % Constants.TIME_UNITS_PER_S);
    elements.add((long) dt.getDayOfYear());
    elements.add((long) dt.getDayOfWeek());
    elements.add((long) dt.getWeekOfWeekyear());
    
    stack.push(elements);
    
    return stack;
  }
}

@@ -1228,19 +1228,17 @@
 ction %7B%0A
-  
 %0A
+
   privat
@@ -1283,18 +1283,16 @@
 S = 64;%0A
-  
 %0A  priva
@@ -1311,16 +1311,17 @@
 %3CString,
+ 
 DateTime
@@ -1470,16 +1470,22 @@
 ldest) %7B
+%0A     
  return 
@@ -1518,20 +1518,21 @@
 IES;
+%0A   
  %7D
-;
 %0A  %7D;%0A
-  
 %0A
+
   pu
@@ -1583,19 +1583,17 @@
 e);%0A  %7D%0A
-  
 %0A
+
   @Overr
@@ -1670,21 +1670,17 @@
 ption %7B%0A
-    
 %0A
+
     Obje
@@ -1698,29 +1698,25 @@
 ack.peek();%0A
-    
 %0A
+
     String t
@@ -1725,21 +1725,17 @@
 = null;%0A
-    
 %0A
+
     if (
@@ -1999,21 +1999,17 @@
 et(tz);%0A
-    
 %0A
+
     if (
@@ -2114,29 +2114,25 @@
 dtz);%0A    %7D%0A
-    
 %0A
+
     obj = st
@@ -2142,25 +2142,17 @@
 .pop();%0A
-        
 %0A
+
     if (
@@ -2287,21 +2287,17 @@
 ;%0A    %7D%0A
-    
 %0A
+
     long
@@ -2318,17 +2318,9 @@
 bj;%0A
-        
 %0A
+
     
@@ -2349,21 +2349,17 @@
 seconds%0A
-    
 %0A
+
     long
@@ -2400,20 +2400,161 @@
 PER_MS;%0A
+%0A
     
+// We want the floor, not truncate: update millis if needed.%0A    if (0 %3E ts && 0 != ts %25 Constants.TIME_UNITS_PER_MS) %7B%0A      tsms--;%0A    %7D%0A
 %0A    Dat
@@ -2630,21 +2630,17 @@
 n array%0A
-    
 %0A
+
     List
@@ -2680,21 +2680,17 @@
 ong%3E();%0A
-    
 %0A
+
     elem
@@ -2968,20 +2968,97 @@
 nts.add(
-ts %25
+(long) dt.getMillisOfSecond()* Constants.TIME_UNITS_PER_MS + Math.abs(ts - tsms *
  Constan
@@ -3075,17 +3075,19 @@
 ITS_PER_
-S
+MS)
 );%0A    e
@@ -3218,21 +3218,17 @@
 ear());%0A
-    
 %0A
+
     stac
@@ -3245,20 +3245,16 @@
 ments);%0A
-    
 %0A    ret

Fix millis for negative timestamp.