8168faf746319a49c43b6c2b6dc512863238297b
[aquarium] / src / main / scala / gr / grnet / aquarium / logic / accounting / dsl / Timeslot.scala
1 /*
2  * Copyright 2011-2012 GRNET S.A. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or
5  * without modification, are permitted provided that the following
6  * conditions are met:
7  *
8  *   1. Redistributions of source code must retain the above
9  *      copyright notice, this list of conditions and the following
10  *      disclaimer.
11  *
12  *   2. Redistributions in binary form must reproduce the above
13  *      copyright notice, this list of conditions and the following
14  *      disclaimer in the documentation and/or other materials
15  *      provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
18  * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
19  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
21  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
24  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  *
30  * The views and conclusions contained in the software and
31  * documentation are those of the authors and should not be
32  * interpreted as representing official policies, either expressed
33  * or implied, of GRNET S.A.
34  */
35
36 package gr.grnet.aquarium.logic.accounting.dsl
37
38 import java.util.Date
39 import scala.collection.mutable
40 import annotation.tailrec
41 import gr.grnet.aquarium.util.date.MutableDateCalc
42
43 /**
44  * A representation of a timeslot with a start and end date.
45  *
46  * @author Georgios Gousios <gousiosg@gmail.com>
47  */
48 final case class Timeslot(from: Date, to: Date) extends Ordered[Timeslot] {
49
50   /* Preconditions to ensure correct object creations */
51   assert(from != null)
52   assert(to != null)
53   assert(start <= end, "from = %s, to = %s".format(new MutableDateCalc(from), new MutableDateCalc(to)))
54
55   def startsBefore(t: Timeslot) : Boolean =  start < t.start
56
57   def startsAfter(t: Timeslot) : Boolean =   start > t.start
58
59   def endsBefore(t: Timeslot) : Boolean = end < t.end
60
61   def endsAfter(t: Timeslot) : Boolean =  end > t.end
62
63   def after(t: Timeslot): Boolean =  start > t.end
64
65   def before(t: Timeslot): Boolean = end < t.start
66
67   def start : Long =  this.from.getTime
68
69   def end : Long =  this.to.getTime
70
71   /**
72    * Check whether this time slot fully contains the provided one.
73    */
74   def contains(t: Timeslot) : Boolean = this.start <= t.start && this.end >= t.end
75
76
77   def containsTimeInMillis(millis: Long) =  start <= millis && millis <= end
78
79
80   /**
81    * Check whether this timeslot contains the provided time instant.
82    */
83   private[dsl] def includes(t: Date) : Boolean = start <= t.getTime &&  t.getTime <= end
84
85
86   /**
87    * Check whether this timeslot overlaps with the provided one.
88    */
89   def overlaps(t: Timeslot) : Boolean =
90     contains(t) || t.contains(this) || this.includes(t.from) || this.includes(t.to)
91
92
93   /**
94    * Merges this timeslot with the provided one. If the timeslots overlap,
95    * a list with the resulting merge is returned. If the timeslots do not
96      * overlap, the returned list contains both timeslots in increasing start
97    * date order.
98    */
99   def merge(t: Timeslot) : Timeslot  = {
100    assert(overlaps(t),this +" has no overlap with " + t)
101    val nfrom = if (start < t.start) from else t.from
102    val nto   = if (end > t.end) to else t.to
103    Timeslot(nfrom, nto)
104   }
105
106   /**
107    * Split the timeslot in two parts at the provided timestamp, if the
108    * timestamp falls within the timeslot boundaries.
109    */
110    def slice(d: Date) : List[Timeslot] =
111     if (includes(d) && d.getTime != start && d.getTime != end)
112       List(Timeslot(from, d), Timeslot(d,to))
113     else
114       List(this)
115
116
117   /**
118    * Find and return the timeslots within which this Timeslot overrides
119    * with the provided list of timeslots. For example if:
120    * 
121    *  - `this == Timeslot(7,20)`
122    *  - `list == List(Timeslot(1,3), Timeslot(6,8), Timeslot(11,15))`
123    *
124    * the result will be: `List(Timeslot(7,8), Timeslot(11,15))`
125    */
126   def overlappingTimeslots(list: List[Timeslot]) : List[Timeslot] =
127     list.foldLeft(List[Timeslot]()) { (ret,t) =>
128       if (t.contains(this)) this :: ret
129       else if (this.contains(t)) t :: ret
130       else if (t.overlaps(this) && t.startsBefore(this)) slice(t.to).head :: ret
131       else if (t.overlaps(this) && t.startsAfter(this))  slice(t.from).last :: ret
132       else ret
133     }.reverse
134
135
136   /**
137    * Find and return the timeslots whithin which this Timeslot does not
138    * override with the provided list of timeslots. For example if:
139    *
140    *  - `this == Timeslot(7,20)`
141    *  - `list == List(Timeslot(1,3), Timeslot(6,8), Timeslot(11,15))`
142    *
143    * the result will be: `List(Timeslot(9,10), Timeslot(15,20))`
144    */
145   def nonOverlappingTimeslots(list: List[Timeslot]): List[Timeslot] =
146     overlappingTimeslots(list) sortWith {_.start < _.start} match  {
147       case Nil => List(this)
148       case over =>
149         val (head,last) = (over.head,over.last)
150         val hd = if (head.start > this.start) List(Timeslot(this.from, head.from)) else List()
151         val tl = if (last.end < this.end) List(Timeslot(last.to, this.to)) else List()
152         hd ++ over.tail.foldLeft((List[Timeslot](),over.head)) {
153           case ((l,x),y) => (l ++ List(Timeslot(x.to,  y.from)),y)
154         }._1  ++ tl
155     }
156
157   /**
158    * Align a list of consecutive timeslots to the boundaries
159    * defined by this timeslot. Elements that do not overlap
160    * with this timeslot are rejected, while elements not
161    * contained in the timeslot are trimmed to this timeslot's
162    * start and end time.
163    */
164   def align(l: List[Timeslot]): List[Timeslot] = {
165     if (l.isEmpty) return List()
166
167     val result : Option[Timeslot] =
168       if (!this.overlaps(l.head)) None
169       else if (l.head.contains(this)) Some(this)
170       else if (l.head.startsBefore(this)) Some(Timeslot(this.from, l.head.to))
171       else if (l.head.endsAfter(this)) Some(Timeslot(l.head.from, this.to))
172       else Some(this)
173
174     result match {
175       case Some(x) => x :: align(l.tail)
176       case None => align(l.tail)
177     }
178   }
179
180   /* align a time slot in "bound_size" boundaries so that
181    * start0 <= start and end0 >= end */
182   def align(bound_size : Long) : Timeslot = {
183     val start0 = (start / bound_size) * bound_size
184     val add_one = if (end % bound_size == 0) 0 else 1
185     val end0  =  (end / bound_size + add_one) * bound_size
186     Timeslot(start0,end0)
187   }
188
189   /* returns true when the start and end address are
190   *  multiples of bound_size*/
191   def isAligned(bound_size : Long) : Boolean =
192      start % bound_size == 0 && end % bound_size == 0
193
194
195   /**
196    * Compares the starting times of two timeslots.
197    */
198   def compare(that: Timeslot): Int = {
199     if (this.startsBefore(that)) -1
200     else if (this.startsAfter(that)) 1
201     else 0
202   }
203
204   /**
205    * Converts the timeslot to the amount of hours it represents
206    */
207   def hours: Double = (to.getTime - from.getTime).toDouble / 1000.0 / 60.0 / 60.0
208
209   def deltaMillis = to.getTime - from.getTime
210
211
212   def myString : String = "Timeslot(" + this.start + "," + this.end + ")"
213   //override def toString() = myString
214   override def toString() =
215     toDateString
216
217   def toDateString = "Timeslot(%s, %s)".format(new MutableDateCalc(from), new MutableDateCalc(to))
218   def toISODateString = "Timeslot(%s, %s)".format(new MutableDateCalc(from).toISOString, new MutableDateCalc(to).toISOString)
219 }
220
221 object Timeslot {
222   def apply(x: Long, y: Long): Timeslot =
223     new Timeslot(new Date(x), new Date(y))
224
225   def apply(x: Int, y: Int): Timeslot =
226     new Timeslot(new Date(x), new Date(y))
227
228  def mergeOverlaps(list: List[Timeslot]): List[Timeslot] = {
229     def sorter(x: Timeslot, y: Timeslot) : Boolean =   y.from after x.from
230     (list sortWith sorter).foldLeft(List[Timeslot]()) {
231       case (Nil,b) =>
232         List(b)
233       case (hd::Nil,b) =>
234         if (hd overlaps  b) (hd merge b)::Nil
235         else b::hd::Nil
236       case (a @ hd::tl,b) =>
237         if(hd overlaps b) (hd merge b)::tl
238         else b :: a
239     }.reverse
240   }
241 }