class ReportsController < ApplicationController
  include ChangeNetwork
  include CacheExistence
  before_filter :authenticate_user!
  before_filter :check_network_presence?, only: [:create, :report], if: Proc.new { |c| c.request.format.json? }
  before_filter :dashboard_topbar
  before_filter :set_report, :only => [:download_pdf,:send_email]
  load_and_authorize_resource :class => Report, except: [:change_network]
  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])
    if request.format.json?
      render json: {data: {reports: @reports.map(&:json_build), scheduled_reports: @scheduled_reports.map(&:json_build)}}
    end
  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"
      json_data = {data: report.json_build , status: 200}
    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>"
        json_data = {data: report.json_build , status: 200}        
      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"
          json_data = {message: "Oops! Report Scheduled is not found in this network" , status: 422}
        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"
          json_data = {data: scheduled_report.json_build , status: 200}
        else
          flash[:notice] = "Oops! There was a problem Scheduing report,Please try after some time"
          json_data = {message: "Oops! There was a problem Scheduing report,Please try after some time", status: 422}
        end
      end
    end
    if request.format.json?
      render json: json_data, status: json_data[:status]
    else
      redirect_to :controller=>:reports, :action=>:report
    end
  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
    if request.format.json?
      link = url_for(controller: 'reports', action: 'download_pdf', id: @report.id, type: params[:type], only_path: true)    
      render json: { data: {link: link}, status: 200}
    end
  end

  def export
    filename = "Report-#{params[:id]}.#{params[:format]}"
    return render json: { error: "Filename is required" }, status: :bad_request if filename.blank?

    if filename.include?("..") || filename.include?("/") || filename.include?("\\")
      return render json: { error: "Invalid filename" }, status: :bad_request
    end

    allowed_extensions = %w[csv pdf xlsx]
    ext = File.extname(filename).delete('.').downcase
    unless allowed_extensions.include?(ext)
      return render json: { error: "Unsupported file type" }, status: :bad_request
    end

    file_path = Rails.root.join("public", "reports", filename)
    if File.exist?(file_path)      
      mime_type = Mime::Type.lookup_by_extension(ext) || "application/octet-stream"
      send_file file_path, filename: filename, type: mime_type.to_s, disposition: "attachment"
    else
      render json: { error: "File not found" }, status: :not_found
    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"
      json_data = {message: "Scheduled report details not found on this network", status: 422}
    else
      flash[:success] = "Successfully removed the report scheduled" if report.delete
      json_data = {data: {}, status: 200}
    end
    if request.format.json?
      render json: json_data, status: json_data[:status]
    else
      redirect_to reports_report_path
    end
  end

  def change_network
    change_user_network
  end

  private

  def current_ability
    if cache_exist?
      @current_ability ||= Ability::ReportAbility.new(current_user)
    else
      @current_ability ||= Ability.new(current_user)
    end
  end

  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
