class ReportsController < ApplicationController
  include ChangeNetwork
  before_action :authenticate_user!
  before_action :dashboard_topbar
  before_action :set_report, :only => [:download_pdf,:send_email]
  load_and_authorize_resource :class => Report
  skip_load_resource :only => [:create,:change_network]

  def report
    unless @current_network.blank?
      @reports = @current_network.reports.order('id DESC')
      @scheduled_reports = @current_network.scheduled_reports.order('id DESC')
    end
    @startDate = 6.days.ago;@endDate = 0.day.ago
    @noti_group = current_user.organisation.notification_groups.pluck(:id,:name)
    @report = params[:scheduled_report_id].blank? ? ScheduledReport.new : @current_network.scheduled_reports.find_by_id(params[:scheduled_report_id])
  end

  def create
    create_update_report
  end

  def create_update_report
    unless params[:make_schedule] == "true"
      report = @current_network.reports.create({"title"=>params[:report][:title].reject { |e| e.to_s.empty? }.join(','),"download_type"=>params[:report][:download_type].reject { |e| e.to_s.empty? }.join(','), "from_time"=>params[:start_date], "to_time"=>params[:end_date]})
      ReportWorker.perform_async(report.id,report.title,params[:offset])
      flash[:success] = "Successfully created report from #{params[:start_date].to_date .strftime("%b %d %Y")} to #{params[:end_date].to_date.strftime("%b %d %Y")}.Plese refresh the page to download the report"
    else
      if params[:report][:id].blank?
        report = @current_network.scheduled_reports.create({"title"=>params[:report][:title].reject { |e| e.to_s.empty? }.join(','), "from_time"=>params[:start_date], "to_time"=>params[:end_date],:scheduled_on => params[:report][:scheduled_on],:notification_group_ids => params[:report][:notification_group_ids]})
        flash[:success] = "Successfully scheduled report for <b>#{params[:schedule] == 'Customize' ? params[:start_date].to_date .strftime("%b %d %Y") + ' to ' + params[:end_date].to_date.strftime("%b %d %Y") : params[:schedule]} </b>"
      else
        scheduled_report = @current_network.scheduled_reports.find_by_id(params[:report][:id])
        if scheduled_report.blank?
          flash[:notice] = "Oops! Report Scheduled is not found in this network"
        elsif scheduled_report.update({"title"=>params[:report][:title].reject { |e| e.to_s.empty? }.join(','), "from_time"=>params[:start_date], "to_time"=>params[:end_date],:scheduled_on => params[:report][:scheduled_on],:notification_group_ids => params[:report][:notification_group_ids]})
          flash[:success] = "Successfully updated the report scheduled"
        else
          flash[:notice] = "Oops! There was a problem Scheduing report,Please try after some time"
        end
      end
    end
    redirect_to :controller=>:reports, :action=>:report
  end

  def download_pdf
    if params[:type] == 'pdf'
      send_file(@report.path,filename: "report.pdf",type: "application/pdf")
    elsif params[:type] == 'excel'
      begin
        send_file(@report.path.split('.')[0]+'.xlsx',filename: "report.xlsx",type: "application/xlsx")
      rescue StandardError => e
        flash[:warning] = "Requested report not found!"
        redirect_to :controller=>:reports, :action=>:report
      end
    else
      send_file(@report.path.split('.')[0]+'.csv',filename: "report.csv",type: "application/csv")
    end
  end

  def send_email
    flash[:notice] = "Requested report emailed to user #{current_user.email}"
    UserMailer.delay.pdf_email(@report.id,current_user.id,current_user.organisation_id)
    redirect_to :controller=>:reports, :action=>:report
  end

  def generate_pdf
    # render :layout=>"pdf"
  end

  def remove_scheduled

    report = @current_network.scheduled_reports.find_by_id(params[:scheduled_id])
    if report.blank?
      flash[:notice] = "Scheduled report details not found on this network"
    else
      flash[:success] = "Successfully removed the report scheduled" if report.delete
    end
    redirect_to reports_report_path
  end

  def change_network
    change_user_network
  end

  private

  def set_report
    @report = Report.where(:id => params[:id]).first
    if @report.blank?
      flash[:warning] = "Requested report not found!"
      redirect_to :controller=>:reports, :action=>:report
    end
  end
end
