class NotificationGroup < ActiveRecord::Base
  has_and_belongs_to_many :users, join_table: :users_notification_groups
  has_and_belongs_to_many :scheduled_reports, join_table: :scheduled_reports_notification_groups
  has_and_belongs_to_many :alerts, join_table: :alerts_notification_groups
  has_many :webhook_endpoints, :dependent => :destroy
  validates :name, uniqueness: { case_sensitive: false, :scope => :organisation_id }
  belongs_to :organisation
  accepts_nested_attributes_for :webhook_endpoints ,:allow_destroy => true
  
  include PublicActivity::Model

  tracked owner: ->(controller, model) { controller && controller.tracked_current_user },params:
    { :attributes => proc {|controller, model_instance| {"notification_group(#{model_instance.name})" => model_instance.changes}}},organisation_id: ->(controller, model) { controller && controller.tracked_current_user.organisation_id },:location_network_id => nil

  tracked assumed_by: proc {|controller, model| controller.user_assumed_by if controller}

  scope :webhook_type, -> { where(notification_type: 'webhook') }

  def webhook_type?
    self.notification_type == 'webhook'
  end

  def json_build
    webhook_endpnts = []
    webhook_endpoints.each do |w|
      webhook_endpnts << w.json_build
    end
    {id: self.id, name: self.name, notification_type: self.notification_type, mobile: self.mobile, email: self.email, organisation_id: self.organisation_id, webhook_endpoints: webhook_endpnts}
  end

  def self.send_notification data
    if data[:type] == 'Report'
      object = ScheduledReport.find_by_id(data[:object_id])
    else
      object = Alert.find_by_id(data[:object_id])
    end

    (object.try(:notification_groups) || []).each do |g|
      if g.notification_type == 'email' || g.notification_type == 'mobile' || g.notification_type == 'both'
        users = g.users
        # next if users.blank?
      end
      if data[:notification_id].present?
        if g.notification_type == 'email' || g.notification_type == 'both'
          custom_email = g.email.blank? ? [] : g.email.split(',')
          user_email = users.pluck(:email)
          email = custom_email + user_email
          if data[:type] == 'Report'
            UserMailer.delay.pdf_email(data[:report_id],email.uniq,g.organisation_id)
          else
            UserMailer.delay.notification_email(email.uniq, data[:notification_id],data[:network_name],g.organisation_id)
          end
        end
        if g.notification_type == 'mobile' || g.notification_type == 'both'
          msg = data[:type] == 'Report' ? "Report scheduled has been generated sucessfully." : Notification.find(data[:notification_id]).try(:message)
          msg += "Please open your registered email to view more Details. --<%= @user.organisation.organisation_name%>"
          custom_mobile = g.mobile.blank? ? [] : g.mobile.split(',')
          user_mobile = users.pluck(:phone_number)
          mobile = custom_mobile + user_mobile
          sms_api = g.organisation.sms_config
          if sms_api.present?
            sender = sms_api.config_hash['ph_no']
            @client = Twilio::REST::Client.new sms_api.config_hash['a_id'], sms_api.config_hash['auth_token']
            (mobile.uniq || []).each do |m|
              if m.present?
                begin
                  @client.messages.create(
                    from: sender,
                    to: ((m.to_s[0] == "+") ?  m.to_s : ("+" + m.to_s)),
                    body: msg
                  )
                rescue Exception => e
                  puts e.backtrace
                end    
              end
            end
          end  
        end
      end
      if g.notification_type == 'webhook'
        if object.is_a?(Alert)
          if data[:notification_id].present?
            payload_data = Notification.where(id: data[:notification_id]).last.try(:json_build)
            WebhookEventWorker.new.perform(g, 'alert', payload_data, object.location_network_id, object.location_network.organisation_id) unless payload_data.blank?
          else
            payload_data = data[:payload]
            WebhookEventWorker.new.perform(g, 'activity_alert', payload_data, object.location_network_id, object.location_network.organisation_id) unless payload_data.blank?
          end
        end
      end
    end
  end

  def self.send_test_webhook_alert alert, notification
    payload_data = notification.try(:json_build)
    alert.notification_groups.webhook_type.each do |ng|
      WebhookEventWorker.new.perform(ng, 'alert', payload_data, alert.location_network_id, alert.location_network.organisation_id, true) unless payload_data.blank?
    end

    payload_data
  end
end
