class AlertsController < ApplicationController
  include ChangeNetwork
  
  before_action :authenticate_user!
  before_action :check_network_presence?, only: [:notifications], if: Proc.new { |c| c.request.format.json? }
  before_action :dashboard_topbar, if: Proc.new { |c| !c.request.format.json? }
  before_action :set_alert , :only => [:edit,:update,:destroy,:test_webhook_event]
  skip_load_and_authorize_resource param_method: :notification_group_params
  load_resource :class => Alert, :except => [:change_network, :read_message, :new, :create,:notification_group,:create_update_notification_group,:delete_notification_group]
  check_policy_for :create, :update, :destroy, with: Alert, id_param: :id
  skip_authorize_resource :only => [:change_network,:notifications,:notification_list,:notification_group,:create_update_notification_group,:delete_notification_group,:header_notification_list]
  authorize_resource :class => Alert, :except => [:notifications]
  authorize_resource :class => Notification, :only => [:notifications]

  def index
    unless @current_network.blank?
      if params[:id].blank?
        @alert = Alert.new(:severity_color => "#e93400")
        @alert.alert_rules.build
      else
        @alert = @current_network.alerts.where(:id => params[:id]).first
        if @alert.blank?
          flash[:notice] = "Your Current network has been changed to #{@current_network.network_name}. Please try again!."
          redirect_to :action => "change_network", :id => @current_network.id
        else
           @alert.alert_rules.build unless @alert.alert_rules.any?
        end
      end
      @alerts = @current_network.alerts
      @noti_group = current_user.organisation.notification_groups.pluck(:id,:name, :notification_type)
    end
  end

  def new
    @alert = @current_network.alerts.new
  end

  def edit
  end

  def read_message
    notification = Notification.where(:id => params[:id]).first
    render :json => {:status=>"notice",:msg => "Oops! Requested Notification not found.",:reload => false,:header => false} and return if notification.blank?
    if params[:header] == "true"
      notification.update_attribute :is_read, true
      count = current_user.total_unread_notifications.count(:id)
          render :json => {:status=>"success",:header => true,:reload => false,:unread_msg => count.to_s}
    else
      unless @current_network.alerts.where(:id =>  notification.alert_id).blank?
        notification.update_attribute :is_read,true
        count = current_user.total_unread_notifications.count(:id)
          render :json => {:status=>"success",:msg => "Notification is marked read.",:reload => false,:header => false,:unread_msg => count.to_s}
      else
        render :json => {:status=>"notice", :msg => "Oops! Requested notification not found since the network got changed, so the page will be refreshed in 5 seconds ",:reload => true,:header => false,:id => "#{@current_network.id}"}
      end
    end
  end

  def header_notification_list
    @notifications = current_user.total_unread_notifications.limit(5)
    #@notifications = Notification.where(:alert_id.in => Alert.find_all_by_location_network_id(current_user.organisation.location_networks.map(&:id)).map(&:id),:is_read => true).desc("created_at") if @notifications.blank?
    render :partial => "shared/notification_content", :layout => false
  end

  def read_all_message
    Notification.where(:alert_id.in => Alert.find_all_by_location_network_id(current_user.organisation.location_networks.map(&:id)).map(&:id),:is_read => false).update_all(:is_read => true)
    render :json => {:status=>"success",:header => true,:reload => false,:unread_msg => "0"}
  end

  def create
    alert_params[:actions].delete("") rescue nil
    @alert = @current_network.alerts.new(alert_params)
    @alert.location_network_id = @current_network.id
    @alert.actions.delete("")
    if @alert.save
      flash[:success] = "Your alerts was created Successfully."
      redirect_to alerts_path
    else
      flash[:error] = "Oops! there was some problem in saving alerts"
       Rails.logger.warn "#{@alert.errors.full_messages}"
      render :new
    end
  end

  def update
    alert_params[:actions].delete("") rescue nil
    if @alert.update_attributes(alert_params)
      flash[:success] = "Your alerts was updated Successfully."
      redirect_to alerts_path
    else
      flash[:error] = "Oops! there was some problem in updating alerts"
       Rails.logger.warn "#{@alert.errors.full_messages}"
      render :edit
    end
  end

  def notifications
    unless @current_network.blank?
      count = 10
      @notifi_unread = @current_network.network_unread_notifications.page(1).per(count)
      if request.format.json?
        render json: {data: @notifi_unread.map(&:json_build), status: 200}
      end
    end
  end

  def notification_list
    unless @current_network.blank?
      page_no = params[:page].blank? ? 1 : params[:page].to_i
      @action =  params[:view]
      count = 10
      if @action == 'unread'
        @notifications = @current_network.network_unread_notifications.page(page_no).per(count)
        @notifications = @current_network.network_unread_notifications.page(page_no - 1).per(count) if  @notifications.blank?
      elsif @action == 'read'
        @notifications = @current_network.network_read_notifications.page(page_no).per(count)
        @notifications = @current_network.network_read_notifications.page(page_no - 1).per(count) if  @notifications.blank?
      end
      if request.format.json?
        return render json: {data: @notifications.map(&:json_build), status: 200}
      end
      render :layout => false
    end
  end

  def destroy
    if @alert.destroy
      flash[:success] = "Your alert is deleted Successfully."
      redirect_to alerts_path
    else
      flash[:error] = "Oops! there was some problem in deleting alert"
      Rails.logger.warn "#{@alert.errors.full_messages}"
    end
  end

  def change_network
    change_user_network
  end

  def notification_group
    @noti_group_list = current_user.organisation.notification_groups.includes(:users)
    organisation = current_user.organisation
    @user = organisation.users.pluck(:id,:email)
    @allow_sms = organisation.sms_config.present?
    @selected_user = []
    if params[:notification_group_id].blank?
      @noti_group = NotificationGroup.new
    else
      @noti_group = current_user.organisation.notification_groups.find_by_id(params[:notification_group_id])
      @selected_user = @noti_group.users.pluck(:id,:email)
    end
    if request.format.json?
      render json: {data: {notification_groups: @noti_group_list.map(&:json_build)}}
    end
  end

  def create_update_notification_group
      update_notification_group
  end

  def update_notification_group
    if params[:notification_group][:id].blank?
      group = NotificationGroup.new(notification_group_params)
      group.organisation_id = current_user.organisation_id
      if group.save
        flash[:success] = "Notification group Successfully created"
        json_data = {data: group.json_build , status: 200}
      else
        flash[:error] = "Oops! there was some problem in creating Notification group #{group.errors.full_messages}"
        json_data = {message: "Notification group is not created. Please check again.", status: 422}  
      end
    else
      group = current_user.organisation.notification_groups.find_by_id(params[:notification_group][:id])
      if group.update(notification_group_params)
        flash[:success] = "Notification group Successfully updated"
        json_data = {data: group.json_build , status: 200}
      else
        flash[:error] = "Oops! there was some problem in updating Notification group #{group.errors.full_messages}"
        json_data = {message: "Notification group is not updated. Please check again.", status: 422}  
      end
    end
    if request.format.json?
      render json: json_data, status: json_data[:status]
    else
      redirect_to notification_group_alerts_path
    end
  end

  def delete_notification_group
    group = current_user.organisation.notification_groups.find_by_id(params[:notification_group_id])
    if group.try(:delete)
      PublicActivity::Activity.create(trackable_id: current_user.id, trackable_type: "NotificationGroup", owner_id: current_user.id, owner_type: "User", key: "notification_group.destroy", organisation_id: current_user.organisation_id, location_network_id: current_user.location_networks.present? ? current_user.location_networks.first.id : nil, parameters: {:attributes => {"notification_group(#{group.name})" => {}}}, assumed_by: session[:assume_user])
      flash[:success] = "Notification group Successfully deleted"
      json_data = {data: {}, status: 200}
    else
      flash[:notice] = "Oops! Problem deleting notification group,Please try after some time"
      json_data = {message: "Notification group is not deleted. Please try again.", status: 422}
    end
    if request.format.json?
      render json: json_data, status: json_data[:status]
    else
      redirect_to notification_group_alerts_path
    end
  end

  def test_webhook_event
    if @alert.notification_groups.webhook_type.any?
      payload = @alert.notify?({}, Time.now, true)
      msg = "Test Webhook has been sent successfully"
      if request.format.json?
        render json: {msg: msg, data: {payload: payload}}, status: 200
      else
        flash[:success] = msg
        redirect_to alerts_path
      end
    else
      msg = "Requested alert does not have any assocaited webhook notification group"
      if request.format.json?
        render json: {msg: msg}, status: 422
      else
        flash[:notice] = msg
        redirect_to alerts_path
      end
    end
  end

    private
    # Never trust parameters from the scary internet, only allow the white list through.
    def set_alert
      @alert =  @current_user.alerts.where(:id => params[:id]).first
      if @alert.blank?
        msg = "Requested alert is not found"
        if request.format.json?
          render json: {msg: msg}, status: 404
        else
          flash[:notice] = msg
          redirect_to alerts_path
        end
      end
    end

    def alert_params
      params.require(:alert).permit(:name, :subject,:message, :category, :severity_color, :tag_list, :actions => [],:notification_group_ids => [], :alert_rules_attributes => [:alert_on, :condition, :value, :id])
    end

    def notification_group_params
      params.require(:notification_group).permit(:name,:email,:mobile,:notification_type,user_ids: [], :webhook_endpoints_attributes => [:name, :url, :enabled, :shared_key, :id, :_destroy])
    end
end
