# frozen_string_literal: true

# Dotations
class Dotation < ApplicationRecord
  # == Constants ============================================================
  AMMOUNT_ON_PROJECT = [
    [0, 'poniżej 100 tyś zł', 0, 99_999],
    [1, '100 tyś do 1 mln zł', 100_000, 999_999],
    [2, '1 mln do 10 mln zł', 1_000_000, 10_000_000],
    [3, 'powyżej 10 mln zł', 10_000_000, 999_999_999_999_999]

  ].freeze
  AMMOUNT_ON_PROJECT_HASH = {
    '' => '', 'poniżej 100 tyś zł' => 0, '100 tyś do 1 mln zł' => 1,
    '1 mln do 10 mln zł' => 2, 'powyżej 10 mln zł' => 3
  }.freeze
  # == Attributes ===========================================================

  # == Extensions ===========================================================
  extend FriendlyId
  friendly_id :name, use: :slugged
  # == Relationships ========================================================
  belongs_to :expert, optional: true
  belongs_to :partner
  belongs_to :min_amount_curr, foreign_key: :min_amount_curr_id,
                               class_name: 'Currency'
  belongs_to :max_amount_curr, foreign_key: :max_amount_curr_id,
                               class_name: 'Currency'
  # dotation currency
  belongs_to :min_dot_amount_curr, foreign_key: :min_dot_amount_curr_id,
                                   class_name: 'Currency'
  belongs_to :max_dot_amount_curr, foreign_key: :max_dot_amount_curr_id,
                                   class_name: 'Currency'

  has_and_belongs_to_many :expenses
  has_and_belongs_to_many :company_sizes
  has_and_belongs_to_many :projects
  has_and_belongs_to_many :tags
  has_and_belongs_to_many :company_activities
  # == Validations ==========================================================
  validates :name, presence: true, length: { maximum: 255 }
  validates :formal_name, presence: true, length: { maximum: 255 }
  # == Scopes ===============================================================
  scope :search, (lambda do |search_value|
    where('name LIKE :value OR formal_name LIKE :value',
          value: "%#{search_value}%")
  end)
  scope :extra_search, (lambda do |search_value|
    where('dotations.name LIKE :value OR dotations.formal_name LIKE :value OR '\
          'dotations.full_descr LIKE'\
          ' :value OR dotations.positioning_text LIKE :value',
          value: "%#{search_value}%")
  end)
  scope :by_localization, (lambda do |search_value|
    where('dotations.localization LIKE :value', value: "%#{search_value}%")
  end)
  scope :by_prize, (lambda do |val_from, val_to|
    where('dotations.max_amount > :val_f AND dotations.max_amount < :val_t',
          val_f: val_from, val_t: val_to)
  end)
  scope :by_comp_size, (lambda do |val|
    joins(:company_sizes).merge(CompanySize.by_ids(val)).distinct
  end)
  scope :by_comp_active, (lambda do |val|
    joins(:company_activities).merge(CompanyActivity.by_ids(val)).distinct
  end)
  scope :by_projects, (lambda do |val|
    joins(:projects).merge(Project.by_ids(val)).distinct
  end)
  scope :min_prize, ->(val) { where('dotations.min_amount < ?', val) }
  scope :point_desc, -> { order(points: :desc) }
  scope :end_date_asc, -> { order(end_date: :asc) }
  scope :public_dot, -> { where(active: true) }
  scope :by_id, ->(val) { where(id: val) }
  scope :open_recruitment, -> { where('dotations.dotation_start_date <= :dat AND dotations.dotation_end_date >= :dat', dat: Time.now) }
  # == Callbacks ============================================================

  # == Class Methods ========================================================
  def self.search_with_filters(filters)
    ret = Dotation.extra_search(filters[:search])
    ret = ret.by_localization(filters[:localization]) if filters[:localization]
    # ammount
    if filters[:ammount_chk].blank? && !filters[:ammount_price].blank?
      ret = ret.min_prize(filters[:ammount_price])
    elsif !filters[:ammount_chk].blank?
      ret =
        ret.by_prize(
          Dotation::AMMOUNT_ON_PROJECT[filters[:ammount_chk].to_i][2],
          Dotation::AMMOUNT_ON_PROJECT[filters[:ammount_chk].to_i][3]
        )
    end
    unless filters[:company_sizes].blank?
      ret = ret.by_comp_size(filters[:company_sizes])
    end
    unless filters[:company_activities].blank?
      ret = ret.by_comp_active(filters[:company_activities])
    end
    ret = ret.by_projects(filters[:projects]) unless filters[:projects].blank?
    ret
  end

  def self.display_as_quarter(date)
    ret = case date.month
          when 1, 2, 3 then 'I '
          when 4, 5, 6 then 'II '
          when 7, 8, 9 then 'III '
          when 10, 11, 12 then 'IV '
          end
    ret += "kwartał #{date.year}"
    ret
  end

  # == Instance Methods =====================================================

  def start_date_ret
    return if start_date.blank?

    if start_date_quarter.eql?(true)
      Dotation.display_as_quarter(start_date)
    else
      start_date.strftime("%d-%m-%Y")
    end
  end

  def end_date_ret
    return if end_date.blank?

    if end_date_quarter.eql?(true)
      Dotation.display_as_quarter(end_date)
    else
      end_date.strftime("%d-%m-%Y")
    end
  end

  def ann_date_ret
    return if announcement_date.blank?

    if ann_date_quarter.eql?(true)
      Dotation.display_as_quarter(announcement_date)
    else
      announcement_date.strftime("%d-%m-%Y")
    end
  end

  def safe_id
    friendly_id
  end

  def replace_video
    require 'nokogiri'
    ret = full_descr
    doc = Nokogiri::HTML(ret)
    doc.css('iframe').each do |iframe|
      url = 'https:' + iframe['src']
      new_node = doc.create_element 'a'
      new_node['href'] = url
      new_node.inner_html = url
      iframe.replace new_node
    end
    doc
  end
end
