require 'pixways'
require 'pixways/searches_helper'

module ApplicationHelper

  include Pixways

  def bg_color
    current_user && current_user.setting.display_params['background_color'] || '#ccc'
  end

  def fg_color
    current_user && current_user.setting.display_params['font_color'] || '#000'
  end

  def abs_image_tag(source, options = {})
    @host_with_port ||= request.protocol << request.host_with_port
    source = "/#{source}" unless source =~ %r{^/}
    image_tag("#{@host_with_port}#{source}", options)
  end

  def dynamic_css
    @pw_bgcolor = current_user.setting.display_params['background_color']
    @pw_ftcolor = current_user.setting.display_params['font_color']
    style = "<style type='text/css'>
    #pw_search_form, .dropdown-menu, .popover-content, #navigation2, .panel-heading, .panel-body, .panel-header, .pw_panel-header, .pw_panel-content, .pw_menu_2, ul.pw_submenu li, #tabs-thumbs .ui-widget-content, .pw_info_thumb, .pw_content, .content, #pw_search_panel, #pw_light_box_panel, #pw_search_form .ui-state-hover, #pw_search_form .ui-state-focus, #light_box_form_place .ui-state-focus, #light_box_form_place .ui-state-hover, .pw_select_manager_add.ui-state-focus, .pw_panel-header-label.ui-state-focus, .pw_panel-header .pw_panel-header-label, #select_pictures_form, .result_content{
        background-color: #{@pw_bgcolor};
    }
    .panel-default, #pw_search_form, #pw_header .ui-widget-header, #pw_center .ui-widget-header,
    #pw_center .ui-widget-content, #pw_light_box_panel, .pw_content, .content, .pw_panel-header, #pw_search_form .ui-state-hover,
    #pw_search_form .ui-state-focus, #light_box_form_place .ui-state-focus, #light_box_form_place .ui-state-hover,
    #pw_panel_carrousel.ui-state-default, .pw_select_manager_add.ui-state-focus, .pw_panel-header-label.ui-state-focus{
        border-color: #{@pw_bgcolor};
    }
    .carousel-indicators li{
        border-color: #{@pw_ftcolor};
    }
    .carousel-indicators .active{
        background-color: #{@pw_ftcolor};
    }
    #pw_statistics_list tbody, #pw_search_form, #pw_media_all, #navigation2 a, .pw_panel-header, .pw_panel-content, .pw_content, .content, .pw_content a, .content a,
    .pw_menus li a:link, .pw_menus li a:visited,
    .pw_menu_2 li, .pw_menu_2 li a:visited, .pw_menu_2 li a:link,
    .pw_submenu li a,
    .pw_menus_3 li a:link, .pw_menus_3 li a:visited,
    .pw_thumb p, .pw_stats_thumb p,
    .pw_stats_export a:link, .pw_stats_export a:visited,
    .pw_info_thumb, .pw_panel-header .ui-state-active, .pw_total_photos, .gap, .pw_toggle_check, .pw_stats_total,
    .pw_panel-header-content a.pw_tpgn_link, .pw_title_panel, #requestprovider,
    #select_pictures_form, .carousel-caption, .reportages_main_title a,.reportages_selection a,
    .show_hide_help.glyphicon.glyphicon-question-sign, #pw_search_panel, #table_request .pw_theme, #pw_paginator .open_close a{
        color: #{@pw_ftcolor};
    }
    </style>"
  end

  def same_bg_css
    style = "<style type='text/css'>
    body, .pw_close_window, .panel{
        background-color: #{@pw_bgcolor};
    }
    .ui-state-hover{
        border-color: #{@pw_bgcolor};
    }
    </style>"
  end

  def get_dossier
    dossiers = {}
    csv_text = File.read('print_outdos.csv')
    csv = CSV.parse(csv_text, col_sep: ';', headers: false)
    csv.each do |row|
      dossiers[row[0]] = row[1]
    end
    dossiers
  end

  def asset_exists?(file_name)
    Rails.application.assets.resolve(file_name).present?
  end

  def pixtech_select_list
    # PixtechParam.where(name:'full_name').pluck(:value).order(:value)
    Pixtech.joins(:pixtech_params).where(pixtech_params: {name:'full_name'}).order('pixtech_params.value').pluck('pixtech_params.value,pixteches.name') rescue ''
  end

  def pixtech_url_out
    pixtech_url_out = Pixways.get_pixtech_param_value(session[:pixtech],'url_out')
    pixtech_url_out.blank? ? '#' : pixtech_url_out
  end

  def home_logo_url
    case session[:pixtech]
    when '',nil
      home_url
    else
      pixtech_home_logo_url = Pixways.get_pixtech_param_value(session[:pixtech],'home_logo_url')
      pixtech_home_logo_url.blank? ? home_url : pixtech_home_logo_url
    end
  end

  def pp2_url
    if session[:login_pp2].blank?
      PP2_URL
    else
      "#{PP2_URL}login?from=pix&login=#{session[:login_pp2]}"
    end
  end

  def get_home_page_logo
    case session[:pixtech]
    when '',nil
      case Server.find_by(is_self: true).name
      when PP2_SERVER_NAME
        'pp2.png'
      when PTREF_SERVER_NAME
        'pixtrakk.png'
      else
        'pixpalace.png'
      end
    else
      pixtech_home_page_logo = Pixways.get_pixtech_param_value(session[:pixtech],'home_page_logo')
      pixtech_home_page_logo.blank? ? 'pixtech.png' : (File.file?("#{Rails.public_path}#{PICTURES_PATH}#{pixtech_home_page_logo}") ? "#{PICTURES_PATH}#{pixtech_home_page_logo}" : 'pixtech.png')
    end
  end

  def show_element(param, shown_by_default=true)
    element_state = session[:pixtech].blank? ? shown_by_default.to_s : Pixways.get_pixtech_param_value(session[:pixtech],param)
    element_state.blank? ? shown_by_default : element_state == 'true'
  end

  def get_footer(session_pixtech='')
    case session_pixtech
    when '',nil
        "Contact PixPalace : #{PixPalaceContact['FR'][:phone]} — #{mail_to PixPalaceContact['FR'][:mail]} | &copy;#{I18n.t'pixpalace'} #{Time.now.year} - #{get_version}"
    else
      pixtech_footer = Pixways.get_pixtech_param_value(session_pixtech,'footer')
      pixtech_footer.blank? ? "Contact PixTech : #{PixPalaceContact['FR'][:phone]} — #{mail_to 'info@pixtech.fr'} | &copy;PixTech #{Time.now.year} - #{get_version}" : "#{pixtech_footer} | &copy;PixTech #{Time.now.year} - #{get_version}"
    end
  end

  def get_version
    pp_revision = File.file?(File.join(Rails.root, 'REVISION')) ? ".#{IO.read(File.join(Rails.root, 'REVISION'))}" : ''
    "v#{PP_VERSION}#{pp_revision[0..4]}"
  end

  def pp_favicon(session_pixtech='')
    case session_pixtech
    when '',nil
      case Server.find_by(is_self: true).name
      when PP2_SERVER_NAME
        'pp2_favicon.png'
      when PTREF_SERVER_NAME
        'pt_favicon.png'
      else
        'pp_favicon.png'
      end
    else
      pixtech_favicon = Pixways.get_pixtech_param_value(session_pixtech,'favicon')
      pixtech_favicon.blank? ? 'pixtech_favicon.png' : asset_exists?(pixtech_favicon) ? pixtech_favicon : 'pixtech_favicon.png'
    end
  end

  def pp_title(session_pixtech='')
    case session_pixtech
    when '',nil
      case Server.find_by(is_self: true).name
      when PP2_SERVER_NAME
        "#{I18n.t 'pixpalace2'}"
      when PTREF_SERVER_NAME
        'Pixtrakk'
      else
        "#{I18n.t 'pixpalace'}"
      end
    else
      if Server.itself?(PIXADMIN_SERVER_NAME)
        'Base interne'
      else
        pixtech_full_name = Pixways.get_pixtech_param_value(session_pixtech,'full_name')
        pixtech_full_name.blank? ? "Pixtech" : pixtech_full_name
      end
    end
  end

  def show_pp_category
    Server.itself?(PIXADMIN_SERVER_NAME)
  end

  def show_paris2024
    # session[:pixtech].blank? ? true : (Server.itself?(PIXADMIN_SERVER_NAME) ? true : Pixways.get_pixtech_param_value(session[:pixtech],'show_paris2024', false) )
    false
  end

  def pdf_file
    #ToDo add new fields to pixtech_params table for admin and client pdf : session[:pixtech_help] and session[:pixtech_help_admin]
    pdf_file = Server.itself?(PIXADMIN_SERVER_NAME) ? "/#{t('help_admin_pdf')}" :"/#{t('help_pdf')}"
  end

  def sort_list
    if session[:pixtech] && !session[:pixtech].blank?
      if (Server.itself?(PIXADMIN_SERVER_NAME) || Server.itself?(PP2_SERVER_NAME))
        [[I18n.t('sort_reception_date'), 'reception_date'],
         [I18n.t('sort_asc_date'), 'asc_date'],
         [I18n.t('sort_created_at'), 'created_at'],
         [I18n.t('sort_asc_created_at'), 'asc_created_at'],
         [I18n.t('sort_updated_at'), 'updated_at'],
         [I18n.t('sort_asc_updated_at'), 'asc_updated_at'],
         [I18n.t('sort_original_filename'), 'original_filename'],
         [I18n.t('sort_asc_filename'), 'asc_filename'],
         [I18n.t('sort_relevance'), 'relevance'],
         [I18n.t('sort_date_created'), 'date_created'],
         [I18n.t('sort_asc_created'), 'asc_created'],
         [I18n.t('sort_random'), 'random']]
      else
        [[I18n.t('sort_reception_date'), 'reception_date'],
         [I18n.t('sort_asc_date'), 'asc_date'],
         [I18n.t('sort_relevance'), 'relevance'],
         [I18n.t('sort_date_created'), 'date_created'],
         [I18n.t('sort_asc_created'), 'asc_created'],
         [I18n.t('sort_random'), 'random']]
      end
    elsif (Server.itself?(PIXADMIN_SERVER_NAME) || Server.itself?(PTREF_SERVER_NAME) || Server.itself?(PP2_SERVER_NAME))
      [[I18n.t('sort_reception_date'), 'reception_date'],
       [I18n.t('sort_asc_date'), 'asc_date'],
       [I18n.t('sort_created_at'), 'created_at'],
       [I18n.t('sort_asc_created_at'), 'asc_created_at'],
       [I18n.t('sort_updated_at'), 'updated_at'],
       [I18n.t('sort_asc_updated_at'), 'asc_updated_at'],
       [I18n.t('sort_original_filename'), 'original_filename'],
       [I18n.t('sort_asc_filename'), 'asc_filename'],
       [I18n.t('sort_relevance'), 'relevance'],
       [I18n.t('sort_date_created'), 'date_created'],
       [I18n.t('sort_asc_created'), 'asc_created'],
       [I18n.t('sort_random'), 'random'],
       [I18n.t('sort_n_per_agency', provider_word: I18n.t(session[:provider_word], count: 1)), 'n_per_agency']]
    else
      [[I18n.t('sort_reception_date'), 'reception_date'],
       [I18n.t('sort_asc_date'), 'asc_date'],
       [I18n.t('sort_relevance'), 'relevance'],
       [I18n.t('sort_date_created'), 'date_created'],
       [I18n.t('sort_asc_created'), 'asc_created'],
       [I18n.t('sort_random'), 'random'],
       [I18n.t('sort_n_per_agency', provider_word: I18n.t(session[:provider_word], count: 1)), 'n_per_agency']]
    end
  end

  def textilize(text)
    Textilizer.new(text).to_html.html_safe unless text.blank?
  end

  def default_setting_per_page
    current_user.setting.default_per_page
  end

  def default_setting_since
    current_user.setting.default_since
  end

  def default_setting_sort
    current_user.setting.default_sort
  end

  def default_setting_media
    current_user.setting.default_media
  end

  def default_setting_thumb
    current_user.setting.under_my_thumb
  end

  def default_setting_pagination
    current_user.setting.pagination
  end

  def pw_link_to_button_in_tabs(name, link)
    raw "<input type='button' class='link_button_in_tabs' data-href='#{link}' value='#{name}' /> #{link_to name, link, class: 'link_button'}"
  end

  def img_date(cdat)
    cdat.strftime('%d/%m/%Y')
  end

  def url_with_protocol(url_to_go)
    url_to_go.blank? ? '' : url_to_go.start_with?('http','https')? url_to_go : "//#{url_to_go}"
  end

end