class UserStayedTime1
  include Mongoid::Document
  field :starttime, type: Time
  field :endtime, type: Time
  field :stayedtime, type: Float, :default =>0.0
  field :created_at, type: Time
  field :rl_mac_id, type: String
  field :vd_mac_id, type: String
  field :register_flag, type: Integer, :default => 0
  field :stayed_flag, type: String
  field :return_flag, type: Integer, :default => 0
  belongs_to :visitor_detail

  index({"rl_mac_id" => 1, "starttime" => 1, "endtime" => 1}, {background: true})
  before_save :set_stayed_flag
  
  def set_stayed_flag
    self.stayed_flag = self.id
  end  

  def self.register_ppl(rlids,start_date,end_date,offset)
    
    total_visits = self.collection.aggregate({"$match" => {'register_flag'=>{ "$exists"=> true},"rl_mac_id" => {"$in" => rlids},"starttime"=> { "$gte" => start_date},"endtime" => {"$lte" => end_date} } }, {"$project"=>{"starttime"=>{"$add" => ["$starttime", offset.to_i]}, "visitor_detail_id"=>1}},{ "$group"=> {"_id"=> { "year"=> {"$year"=>"$starttime"},"month"=> {"$month"=>"$starttime"},"day"=> {"$dayOfMonth"=>"$starttime"}, "visitor_detail_id"=>"$visitor_detail_id"},  "count"=> { "$sum" => 1 }}})

    never_visited = self.collection.aggregate({"$match" => {'register_flag'=>{ "$exists"=> true},"rl_mac_id" => {"$in" => rlids},"starttime"=> { "$gte" => start_date},"endtime" => {"$lte" => end_date} } }, {"$project"=>{"starttime"=>{"$add" => ["$starttime", offset.to_i]}, "visitor_detail_id"=>1}},{ "$group"=> {"_id"=> { "year"=> {"$year"=>"$starttime"},"month"=> {"$month"=>"$starttime"},"day"=> {"$dayOfMonth"=>"$starttime"}, "visitor_detail_id"=>"$visitor_detail_id"},  "count"=> { "$sum" => 1 }}},{"$match" => {"count" =>{"$lte" => 1}}})

    before_visited = self.collection.aggregate({"$match" => {'register_flag'=>{ "$exists"=> true},"rl_mac_id" => {"$in" => rlids},"starttime"=> { "$gte" => start_date},"endtime" => {"$lte" => end_date} } }, {"$project"=>{"starttime"=>{"$add" => ["$starttime", offset.to_i]}, "visitor_detail_id"=>1}},{ "$group"=> {"_id"=> { "year"=> {"$year"=>"$starttime"},"month"=> {"$month"=>"$starttime"},"day"=> {"$dayOfMonth"=>"$starttime"}, "visitor_detail_id"=>"$visitor_detail_id"},  "count"=> { "$sum" => 1 }}},{"$match" => {"count" =>{"$gt" => 1}}})

    return {:before_visited=>before_visited, :never_visited=>never_visited, :total_visits=>total_visits}
  end

  def self.tot_unique_users(vdids,start_date,end_date)
    self.collection.aggregate({"$match" => {"visitor_detail_id" => {"$in" => vdids},"starttime"=> { "$gte" => start_date.to_time.utc.beginning_of_day},"endtime" => {"$lte" => end_date.to_time.utc.end_of_day}, "stayedtime" => {"$gte" => APPLICATION['defaults']['timeinterval'] }  } }, { "$group"=> {"_id"=> { "year"=> {"$year"=>"$starttime"},"month"=> {"$month"=>"$starttime"},"day"=> {"$dayOfMonth"=>"$starttime"}, "visitor_detail_id"=>"$visitor_detail_id"}, "count"=> { "$sum" => 1 }}},{"$match" => {"count" =>{"$lte" => 1}}},"$group"=>{"_id"=>"$_id.day","count"=>{"$sum"=>"$count"}}) rescue []
  end

  def self.tot_before_visited(rlids,start_date,end_date,offset)
    self.collection.aggregate({"$match" => {"rl_mac_id" => {"$in" => rlids},"starttime"=> { "$gte" => start_date},"endtime" => {"$lte" => end_date} } }, {"$project"=>{"starttime"=>{"$add" => ["$starttime", offset.to_i]}, "visitor_detail_id"=>1}}, { "$group"=> {"_id"=> { "year"=> {"$year"=>"$starttime"},"month"=> {"$month"=>"$starttime"},"day"=> {"$dayOfMonth"=>"$starttime"}, "visitor_detail_id"=>"$visitor_detail_id"}, "count"=> { "$sum" => 1 }}},{"$match" => {"count" =>{"$gt" => 1}}},"$group"=>{"_id"=>"$_id.day","count"=>{"$sum"=>1}})
  end

  def self.tot_before_visited_in_store(rlids,start_date,end_date,offset)
    self.collection.aggregate({"$match" => {"rl_mac_id" => {"$in" => rlids},"starttime"=> { "$gte" => start_date},"endtime" => {"$lte" => end_date} } }, {"$project"=>{"starttime"=>{"$add" => ["$starttime", offset.to_i]}, "visitor_detail_id"=>1, "stayedtime"=>1}}, { "$group"=> {"_id"=> { "year"=> {"$year"=>"$starttime"},"month"=> {"$month"=>"$starttime"},"day"=> {"$dayOfMonth"=>"$starttime"}, "visitor_detail_id"=>"$visitor_detail_id"},"stayedtime"=>{"$sum"=>"$stayedtime"} ,"count"=> { "$sum" => 1 }}},{"$match" => {"count" =>{"$gt" => 1}, "stayedtime" => {"$gte" => APPLICATION['defaults']['timeinterval'] }}},"$group"=>{"_id"=>"$_id.day","count"=>{"$sum"=>1}})
  end

  def self.before_visited(vdids,start_date,end_date,offset)
    total_people = self.tot_before_visited(vdids,start_date,end_date,offset)
    in_store = self.tot_before_visited_in_store(vdids,start_date,end_date,offset)
    return {"total_people"=>total_people, "in_store"=>in_store}
  end
  
  def self.tot_never_visited(rlids,start_date,end_date,offset)
     self.collection.aggregate({"$match" => {"rl_mac_id" => {"$in" => rlids},"starttime"=> { "$gte" => start_date},"endtime" => {"$lte" => end_date} } }, {"$project"=>{"starttime"=>{"$add" => ["$starttime", offset.to_i]}, "visitor_detail_id"=>1}}, { "$group"=> {"_id"=> { "year"=> {"$year"=>"$starttime"},"month"=> {"$month"=>"$starttime"},"day"=> {"$dayOfMonth"=>"$starttime"}, "visitor_detail_id"=>"$visitor_detail_id"}, "count"=> { "$sum" => 1 }}},{"$match" => {"count" =>{"$lte" => 1}}},"$group"=>{"_id"=>"$_id.day","count"=>{"$sum"=>1}})
  end

  def self.total_people(rlids,start_date,end_date,offset)
   self.collection.aggregate({"$match" => {"rl_mac_id" => {"$in" => rlids},"starttime"=> { "$gte" => start_date},"endtime" => {"$lte" => end_date} } }, {"$project"=>{"starttime"=>{"$add" => ["$starttime", offset.to_i]}, "visitor_detail_id"=>1}},{ "$group"=> {"_id"=>{"year"=> {"$year"=>"$starttime"},"month"=> {"$month"=>"$starttime"},"day"=> {"$dayOfMonth"=>"$starttime"}} ,"visitors"=> { "$addToSet" => "$visitor_detail_id" }}},{"$unwind" => '$visitors'},"$group"=>{"_id"=>"$_id.day","count"=>{"$sum"=>1}})
  end

  def self.tot_in_store(rlids,start_date,end_date,offset)
    self.collection.aggregate({"$match" => {"rl_mac_id" => {"$in" => rlids},"starttime"=> { "$gte" => start_date},"endtime" => {"$lte" => end_date} } }, {"$project"=>{"starttime"=>{"$add" => ["$starttime", offset.to_i]}, "visitor_detail_id"=>1, "stayedtime"=>1}}, { "$group"=> {"_id"=> { "year"=> {"$year"=>"$starttime"},"month"=> {"$month"=>"$starttime"},"day"=> {"$dayOfMonth"=>"$starttime"}, "visitor_detail_id"=>"$visitor_detail_id"},"stayedtime"=>{"$sum"=>"$stayedtime"} ,"count"=> { "$sum" => 1 }}},{"$match" => {"stayedtime" => {"$gte" => APPLICATION['defaults']['timeinterval'] }}},"$group"=>{"_id"=>"$_id.day","count"=>{"$sum"=>1}})
  end

  def self.never_visited(rlids,start_date,end_date,offset)
    total_people = self.tot_never_visited(rlids,start_date,end_date,offset)
    in_store = self.collection.aggregate({"$match" => {"rl_mac_id" => {"$in" => rlids},"starttime"=> { "$gte" => start_date},"endtime" => {"$lte" => end_date} } }, {"$project"=>{"starttime"=>{"$add" => ["$starttime", offset.to_i]}, "visitor_detail_id"=>1, "stayedtime"=>1}}, { "$group"=> {"_id"=> { "year"=> {"$year"=>"$starttime"},"month"=> {"$month"=>"$starttime"},"day"=> {"$dayOfMonth"=>"$starttime"}, "visitor_detail_id"=>"$visitor_detail_id"},"stayedtime"=>{"$sum"=>"$stayedtime"} ,"count"=> { "$sum" => 1 }}},{"$match" => {"count" =>{"$lte" => 1}, "stayedtime" => {"$gte" => APPLICATION['defaults']['timeinterval'] }}},"$group"=>{"_id"=>"$_id.day","count"=>{"$sum"=>1}})
    return {"total_people"=>total_people, "in_store"=>in_store}
  end

  def self.total_traffic(rlids,start_date,end_date,offset)
    total_people = self.total_people(rlids,start_date,end_date,offset)
    in_store = self.tot_in_store(rlids,start_date,end_date,offset)
    return {"total_people"=>total_people, "in_store"=>in_store}
  end

  def self.avg_ppl_by_hr_in_store(rlids,start_date,end_date,offset)
    self.collection.aggregate({"$match" => { "rl_mac_id"=>{"$in" => rlids},"starttime"=> { "$gte" => start_date},"endtime" => {"$lte" => end_date}, "stayedtime" => {"$gte" => APPLICATION['defaults']['timeinterval'] } } }, {"$project"=>{"starttime"=>{"$add" => ["$starttime", offset.to_i]}, "visitor_detail_id"=>1}}, { "$group"=> {"_id"=> { "hour"=>{"$hour"=>"$starttime"}},  "visitors"=> { "$addToSet" => "$visitor_detail_id" }}},{"$unwind" => '$visitors'},"$group"=>{"_id"=>"$_id.hour","count"=>{"$sum"=>1}})
  end

  def self.avg_min_spent_in_store(rlids,start_date,end_date,offset)
    self.collection.aggregate({"$match" => {"rl_mac_id" => {"$in" => rlids},"starttime"=> { "$gte" => start_date},"endtime" => {"$lte" => end_date}, "stayedtime" => {"$gte" => APPLICATION['defaults']['dwell_time']}} }, {"$project"=>{"starttime"=>{"$add" => ["$starttime", offset.to_i]}, "stayedtime"=>1 }}, { "$group"=> {"_id"=> {"hour"=> {"$hour"=>"$starttime"}}, "sum"=> { "$sum" => "$stayedtime" }, "count"=> { "$sum" =>1 }}})
  end

  def self.avg_peple_by_hr(vdids,start_date,end_date,offset)
    self.collection.aggregate({"$match" => {"visitor_detail_id" => {"$in" => vdids},"starttime"=> { "$gte" => start_date},"endtime" => {"$lte" => end_date} } }, {"$project"=>{"starttime"=>{"$add" => ["$starttime", offset.to_i]}, "starttime"=>1}}, { "$group"=> {"_id"=> { "year"=> {"$year"=>"$starttime"},"month"=> {"$month"=>"$starttime"},"day"=> {"$dayOfMonth"=>"$starttime"}, "hour"=>{"$hour"=>"$starttime"}},  "count"=> { "$sum" => 1 }}})
  end

  def self.customer_recency_new(rlids,start_date,offset)
    self.collection.aggregate({"$match" => {'stayed_flag'=>{ "$exists"=> true}, "rl_mac_id" => {"$in" => rlids}, "starttime"=> { "$gte" => start_date} }}, {"$project"=>{"starttime"=>{"$add" => ["$starttime", offset.to_i]}, "stayedtime"=>1, "visitor_detail_id"=>1, "stayed_flag"=>1 }} , { "$group"=> {"_id"=> {"year"=> {"$year"=>"$starttime"}, "week"=>{"$week"=>"$starttime"},"stayed_flag"=>"$stayed_flag"},"visitors"=> { "$addToSet" => "$visitor_detail_id" }, "count"=> { "$sum" => 1 }}},{"$match" => {"count" =>{"$gt" => 1}}},{"$group"=> {"_id"=> {"visitors"=>"$visitors","week"=>"$_id.week","year"=>"$_id.year"}}},{ "$sort" => { "_id.week" => 1 }})
    # self.collection.aggregate({"$match" => {"rl_mac_id" => {"$in" => rlids}, "starttime"=> { "$gte" => start_date} }}, {"$project"=>{"starttime"=>{"$add" => ["$starttime", offset.to_i]}, "stayedtime"=>1, "visitor_detail_id"=>1 }} , { "$group"=> {"_id"=> {"year"=> {"$year"=>"$starttime"}, "week"=>{"$week"=>"$starttime"}},"visitors"=> { "$addToSet" => "$visitor_detail_id" }, "count"=> { "$sum" => 1 }}},{"$match" => {"count" =>{"$gt" => 1}}},{"$group"=> {"_id"=> {"visitors"=>"$visitors","week"=>"$_id.week","year"=>"$_id.year"}}},{ "$sort" => { "_id.week" => 1 } })
  end

  def self.members_customer_recency_new(rlids,start_date,offset)
    UserDetail.collection.aggregate({"$match" => {"rl_mac_id" => {"$in" => rlids},"timestamp"=> { "$gte" => start_date} }}, {"$project"=>{"timestamp"=>{"$add" => ["$timestamp", offset.to_i]}, "visitor_detail_id"=>1 }} , { "$group"=> {"_id"=> { "year"=> {"$year"=>"$timestamp"}, "week"=>{"$week"=>"$timestamp"}},"visitors"=> { "$addToSet" => "$visitor_detail_id" }, "count"=> { "$sum" => 1 }}},{"$group"=> {"_id"=> {"visitors"=>"$visitors","week"=>"$_id.week","year"=>"$_id.year"}}},{ "$sort" => { "_id.week" => 1 } })
  end

  def self.members_customer_recency(rlids,start_date,end_date,offset)
    UserDetail.collection.aggregate({"$match" => {"rl_mac_id" => {"$in" => rlids},"timestamp"=> { "$gte" => start_date, "$lte" => end_date} }}, {"$project"=>{"timestamp"=>{"$add" => ["$timestamp", offset.to_i]}, "visitor_detail_id"=>1}} , { "$group"=> {"_id"=> {},"visitors"=> { "$addToSet" => "$visitor_detail_id" }, "count"=> { "$sum" => 1 }}},{"$group"=> {"_id"=> {"visitors"=>"$visitors"}}})
  end

  def self.customer_recency(rlids,start_date,end_date,offset)
    self.collection.aggregate({"$match" => {'stayed_flag'=>{ "$exists"=> true},"rl_mac_id" => {"$in" => rlids},"starttime"=> { "$gte" => start_date},"endtime" => {"$lte" => end_date} }}, {"$project"=>{"starttime"=>{"$add" => ["$starttime", offset.to_i]}, "stayed_flag"=>1,"visitor_detail_id"=>1}} , { "$group"=> {"_id"=> {},"visitors"=> { "$addToSet" => "$visitor_detail_id" },"stayed_flag"=>"$stayed_flag", "count"=> { "$sum" => 1 }}},{"$match" => {"count" =>{"$gt" => 1}}},{"$group"=> {"_id"=> {"visitors"=>"$visitors"}}})
    # self.collection.aggregate({"$match" => {"rl_mac_id" => {"$in" => rlids},"starttime"=> { "$gte" => start_date},"endtime" => {"$lte" => end_date} }}, {"$project"=>{"starttime"=>{"$add" => ["$starttime", offset.to_i]}, "visitor_detail_id"=>1}} , { "$group"=> {"_id"=> {},"visitors"=> { "$addToSet" => "$visitor_detail_id" }, "count"=> { "$sum" => 1 }}},{"$match" => {"count" =>{"$gt" => 1}}},{"$group"=> {"_id"=> {"visitors"=>"$visitors"}}})
  end

  def self.top_6_visits(rlids,start_date,end_date,offset)
    UserDetail.collection.aggregate({"$match" => {"rl_mac_id" => {"$in" => rlids},"timestamp"=> { "$gte" => start_date, "$lte" => end_date} }}, {"$project"=>{"timestamp"=>{"$add" => ["$timestamp", offset.to_i]}, "visitor_detail_id"=>1}} , { "$group"=> {"_id"=> {"hour"=> {"$hour"=>"$timestamp"}, "visitor_detail_id"=>"$visitor_detail_id" }, "count"=> { "$sum" => 1 }}}, { "$sort"=> { "count"=> -1 } })
    # self.collection.aggregate({"$match" => {"rl_mac_id" => {"$in" => rlids},"starttime"=> { "$gte" => start_date},"endtime" => {"$lte" => end_date} } }, {"$project"=>{"starttime"=>{"$add" => ["$starttime", offset.to_i]}, "visitor_detail_id"=>1,"stayed_flag"=>1}}, { "$group"=> {"_id"=> { "visitor_detail_id"=>"$visitor_detail_id","stayed_flag"=>"$stayed_flag"}, "count"=> { "$sum" => 1 }}}, { "$sort"=> { "count"=> -1 }})
  end
  

  def self.tot_return_users(vdids,start_date,end_date)
    self.collection.aggregate({"$match" => {"visitor_detail_id" => {"$in" => vdids},"starttime"=> { "$gte" => start_date.to_time.utc.beginning_of_day},"endtime" => {"$lte" => end_date.to_time.utc.end_of_day}, "stayedtime" => {"$gte" => APPLICATION['defaults']['timeinterval'] } } }, { "$group"=> {"_id"=> { "year"=> {"$year"=>"$starttime"},"month"=> {"$month"=>"$starttime"},"day"=> {"$dayOfMonth"=>"$starttime"}, "visitor_detail_id"=>"$visitor_detail_id"}, "count"=> { "$sum" => 1 }}},{"$match" => {"count" =>{"$gt" => 1}}}, {"$group"=>{"_id"=> { "year"=> "$_id.year","month"=> "$_id.month", "day"=> "$_id.day" }, "count"=>{"$sum"=>1}}} )
  end

  def self.total_people_in_store(vdids,start_date,end_date,offset)
    self.collection.aggregate({"$match" => {"visitor_detail_id" => {"$in" => vdids},"starttime"=> { "$gte" => start_date},"endtime" => {"$lte" => end_date}, "stayedtime" => {"$gte" => APPLICATION['defaults']['timeinterval'] } } }, {"$project"=>{"starttime"=>{"$add" => ["$starttime", offset.to_i]}, "visitor_detail_id"=>1}}, { "$group"=> {"_id"=> { "year"=> {"$year"=>"$starttime"},"month"=> {"$month"=>"$starttime"},"day"=> {"$dayOfMonth"=>"$starttime"}},  "visitors"=> { "$addToSet" => "$visitor_detail_id" },"count"=>{"$sum"=>1}}},{"$group"=>{"_id"=>"$_id.day","count"=>{"$sum"=>1}} } )
  end

  def self.uniqe_tot_return(vdids,start_date,end_date)
    unique_users = self.tot_unique_users(vdids,start_date,end_date)
    return_users = self.tot_return_users(vdids,start_date,end_date)
    total_users = self.total_people_in_store(vdids,start_date,end_date)
    return {"total_users"=>total_users, "unique_users"=>unique_users, "return_users"=>return_users}
  end

  def self.get_visitors_count_n_sttime(starttime,endtime)
    starttime=starttime*1000
    endtime=endtime*1000

  map = %Q{
    function() {
        var st = this.starttime.getTime(), et = this.endtime.getTime()

        var stm = 0
        if(this.stayedtime){
          if(st >= #{starttime} && #{endtime} > st){
            if(#{endtime} > et)
               stm = (et-st)
            else
              stm = (#{endtime} - st)
          }
          else if(st < #{starttime} && #{endtime} > st){
            if(#{endtime} > et)
              stm = (et- #{starttime})
            else
              stm = (#{endtime} - #{starttime})
          }
          stm = stm/1000
        }

      emit(this.rl_mac_id, {vids : [this.vd_mac_id], sttm: stm, tv: 1})
    }
  }
  reduce = %Q{
    function(key, values) {
      var result = {"vids": [], "sttm":0, tv: 0}
      values.forEach(function(ust) {
        ust.vids.forEach(function(v){
          result.vids.push(v)
        })
        result.sttm +=  ust.sttm
        result.tv += ust.tv
      })
      return result;
    }
  }

        #   /* if(ust.sttm){
        #   var st = ust.st
        #   var et = ust.et
        #   var tm = 0
        #   if(st >= #{starttime} && #{endtime} > st){
        #     if(#{endtime} > et)
        #        tm = (et-st)
        #     else
        #       tm = (#{endtime} - st)
        #   }
        #   else if(st < #{starttime} && #{endtime} > st){
        #     if(#{endtime} > et)
        #       tm = (et- #{starttime})
        #     else
        #       tm = (#{endtime} - #{starttime})
        #   }
        #   tm = tm/1000
        #   result.tust += tm
        #   if(tm >= 300)
        #     result.store += 1
        #   else
        #     result.walk += 1
        # } */
  #   map = %q{
  #   function() {
  #     emit(this.rl_mac_id, {vid : [this._id]})
  #   }
  # }
  # reduce = %Q{
  #   function(key, values) {
  #     var result = {vid : []}
  #     values.forEach(function(ust){
  #       ust.vid.forEach(function(u){
  #         result.vid.push(u)
  #       })
  #     })
  #     return result;
  #   }
  # }
  map_reduce(map,reduce).out(inline: true).to_a
end
end