require 'pixways'

class StatisticsController < ApplicationController

  layout "statistics"

  before_action :load_cached_search_params, only: [:index, :stats_to_csv]
  authorize_resource

  def index
    if params[:per_page]
      per_page = params[:per_page]
    elsif @current_params[:per_page]
      per_page = @current_params[:per_page]
    else
      per_page = 60
    end

    unless @current_params[:search_since]
      if cookies[:stats_since].present?
        @current_params[:search_since] = cookies[:stats_since]
      else
        @current_params[:search_since] = "3_month"
      end
    end
    cookies[:stats_since] = @current_params[:search_since]

    @current_params[:customers_only] = @current_params[:customers_only_default].blank? || @current_params[:customers_only]=='1' ? '1' : false

    l_prov = []
    session[:provhd].each_index{|i| l_prov << i if session[:provhd][i] == 1}
    if l_prov.blank?
      session[:provbd].each_index{|i| l_prov << i if session[:provbd][i] == 1}
    end
    #add PixTech stock(s) stats access to author
    if !session[:pixtech].blank? && !session[:pixtech_author].blank?
      session[:pixtech_author].each do |p|
        pixtech_stock =  Provider.find_by(string_key: Provider.find(p).pp_string_key)
        l_prov << pixtech_stock.id unless pixtech_stock.nil?
      end
    end
    @providers = Provider.where(id: l_prov).order(:name)
    @pw_providers = @providers.where(provider_type_id: 1, local: false)
    @local_providers = @providers.where(provider_type_id: 1, local: true)
    @photographer_providers = @providers.where(provider_type_id: 2).reorder(:pixtech_id, :pp_string_key, :name)

    if current_user.is_superadmin?
      @titles = Title.order_by_name('all')
      @pixtech_titles = Title.order_by_name('all',0,'all')
    else
      @titles = Title.order_by_name('visible')
      @pixtech_titles = Title.order_by_name('all',0,session[:pixtech])
    end

    server = @current_params[:server].to_i
    if server!=0
      @current_params[:titles] = {}
      @current_params[:pixtech_titles] = {}
      if current_user.is_superadmin?
        titles_list = Title.order_by_name('all',server).pluck(:id)
        pixtech_titles_list = Title.order_by_name('all',server,'all').pluck(:id)
      else
        titles_list = Title.order_by_name('visible',server).pluck(:id)
        pixtech_titles_list = Title.order_by_name('all',server,session[:pixtech]).pluck(:id)
      end
      titles_list.map{|t| @current_params[:titles]["#{t}"]=1 } unless titles_list.blank?
      pixtech_titles_list.map{|t| @current_params[:pixtech_titles]["#{t}"]=1 } unless pixtech_titles_list.blank?
    else
      if @current_params[:titles].blank? && @current_params[:pixtech_titles].blank?
        titles_list = @titles.pluck(:id)
        pixtech_titles_list = @pixtech_titles.pluck(:id)
      else
        titles_list = @current_params[:titles].blank? ? [] : @titles.pluck(:id) & @current_params[:titles].keys.collect!{|e| e.to_i}
        pixtech_titles_list = @current_params[:pixtech_titles].blank? ? [] : @pixtech_titles.pluck(:id) & @current_params[:pixtech_titles].keys.collect!{|e| e.to_i}
      end
      # titles_list = @titles.blank? ? [] : (@current_params[:titles].blank? && @current_params[:pixtech_titles].blank?) ? @titles.pluck(:id) : @titles.pluck(:id) & @current_params[:titles].keys.collect!{|e| e.to_i}
      # pixtech_titles_list = @pixtech_titles.blank? ? [] : (@current_params[:titles].blank? && @current_params[:pixtech_titles].blank?) ? @pixtech_titles.pluck(:id) : @pixtech_titles.pluck(:id) & @current_params[:pixtech_titles].keys.collect!{|e| e.to_i}
    end
    @nb_selected_titles = @current_params[:titles].blank? ? '' : titles_list.count > 0 ? "#{titles_list.count} /" : ''
    @nb_selected_pixtech_titles = @current_params[:pixtech_titles].blank? ? '' : pixtech_titles_list.count > 0 ? "#{pixtech_titles_list.count} /" : ''
    titles_all = titles_list + pixtech_titles_list

    unless (current_user.is_superadmin? && @current_params[:providers].blank? && params[:search].blank?) || l_prov.blank? || (titles_all).blank?
      cearch = {}
      sort = 'created_at'
      sort = @current_params[:sort] if @current_params[:sort]
      sort = "by_#{sort}"
      cearch[:per_page] = per_page
      cearch[:page] = params[:page].to_i if params[:page]
      # to display only author stats
      #cearch[:conditions] = session[:pixtech_author].blank? ? Statistic.params_to_conditions(@current_params) : Statistic.params_to_conditions(@current_params, "#{current_user.last_name} #{current_user.first_name}")
      cearch[:conditions] = Statistic.params_to_conditions(@current_params)
      cearch[:with] = Statistic.params_to_with(@current_params, l_prov)
      keywords = @current_params[:key_words] ? Pixways::SearchesHelper.filter_keywords(@current_params[:key_words]) : ''
      @statistics = Statistic.instance_eval(sort).search(keywords, cearch)
      if current_user.is_superadmin?
        facets = Statistic.facets(keywords, cearch.except(:page, :per_page) )
        @nb_stats = facets[:provider_id]
      end
    end

    pixtech_author = !session[:pixtech_author].blank?
    if pixtech_author
      @sort_list = [
        [I18n.t('sort_download_date'), 'created_at'],
        [I18n.t('sort_filename'), 'original_filename'],
        ['téléchargement','operation_label_id'],
        ['titre', 'title_name'],
        [I18n.t(session[:creator_word]),'creator'],
        ['titre photo','headline']
      ]
    else
      @sort_list =[
        [I18n.t('sort_download_date'), 'created_at'],
        [I18n.t('sort_filename'), 'original_filename'],
        ['téléchargement','operation_label_id'],
        ['titre', 'title_name'],
        ['utilisateur', 'user_login'],
        [I18n.t(session[:provider_word], count: 1), 'provider_name'],
        [I18n.t(session[:creator_word]),'creator'],
        ['titre photo','headline']
      ]
    end

    if current_user.is_superadmin?
      @operation_labels_select =  [[t('statistics.all'), 0]] + OperationLabel.all.map{|l| [t("statistics.#{l.label}"), l.id]}
    elsif session[:pixtech]=='parismatch'
      @operation_labels_select =  [[t('statistics.all'), 0]] + OperationLabel.where.not(id: 4).map{|l| [t("statistics.#{l.label}"), l.id]}
    else
      @operation_labels_select =  [[t('statistics.all'), 0]] + OperationLabel.where(id: [1,2,3]).to_a.map{|l| [t("statistics.#{l.label}"), l.id]}
    end

    respond_to do|format|
      format.html {
      }
      format.js {
      }
      format.csv {
        if params[:synthesis]
          send_data Statistic.export_synthesis_to_csv(@statistics, @providers.count), filename: "Statistiques_PixPalace_Synthese_" + Time.now.strftime("%Y-%m-%d_%H-%M") + ".csv", type: 'text/csv; header=present'
        else
          send_data Statistic.export_to_csv(@statistics,pixtech_author, session[:provider_word], session[:creator_word]), filename: "Statistiques_PixPalace_" + Time.now.strftime("%Y-%m-%d_%H-%M") + ".csv", type: 'text/csv; header=present'
        end
      }
    end

  end

  def show
    @stat = Statistic.find(params[:id])
    respond_to do |format|
      format.xml { render xml: @stat }
    end
  end


  def create
    ms_id = Image.find(params[:statistic][:image_id].to_i).ms_image_id
    @stat =  Statistic.new(params[:statistic])
    respond_to do |f|
      if @stat.save
        MessageToMs::PutMessageRec.sendMessageRecord("SEND_TO_PT", ms_id) if Server.itself? PIXADMIN_SERVER_NAME

        f.xml  { render xml: @stat, status: :created, location: @stat }
        f.json { render json: @stat }
      else
        f.xml  { render xml: @stat.errors, status: :unprocessable_entity }
        f.json { render json: @stat.errors }
      end
    end
  end

  private

end
