#!/usr/bin/env ruby

require File.dirname(__FILE__) + '/../config/environment.rb'
# require 'optparse'
# require 'optparse/time'
# require 'csv'

options = {}
options[:sep] = ';'

OptionParser.new do |opts|
  opts.banner = "Usage: export_restrictions_groups [options]"

  opts.on("-s", "--server server_name", String, "server name from which to export data (all servers by default) ") do |l|
    options[:server] = l
  end

  opts.on("-g ;", "--group group_name", String, "group to export") do |l|
    options[:group] = l
  end

  opts.on_tail("-h", "--help", "Show this message") do
    puts opts
    exit
  end

end.parse!

# if ARGV.blank?
#   puts 'error : no arguments, use -h or --help for help'
#   exit
# end

# ARGV.collect do |f|
# export = ""
# export.encode!('UTF-8')
csv_file = "restrictions_#{Time.now.strftime("%Y-%m-%d_%H-%M")}.csv"
providers_list = Provider.where(provider_type_id:1).order(:name).select(:id,:name)
titles_list = Title.joins(:title_provider_group_name).group(:server_id,:title_provider_group_name_id).order("server_id,title_provider_group_names.name").select(:server_id,:title_provider_group_name_id)
csv_content = []
header = ["Server","Group","Title"]
providers_list.each { |p| header.push(p.name)}
csv_content.push(header)
titles_list.each do |t|
  csv_line = []
  csv_line.push((Server.find(t.server_id).name rescue 'deleted'))
  csv_line.push((TitleProviderGroupName.find(t.title_provider_group_name_id).name rescue 'deleted'))
  csv_line.push(Title.where(server_id: t.server_id,title_provider_group_name_id: t.title_provider_group_name_id).select(:name).collect(&:name).join(' / '))
  providers_list.each do |p|
    tpg = TitleProviderGroup.find_by(title_provider_group_name_id: t.title_provider_group_name_id, provider_id: p.id)
    if tpg.nil?
      authorizations = 'hidden'
    else
      auth_lvl = 0
      Authorization.where(title_provider_group_id:tpg.id).collect do |a|
        auth_lvl += a.permission_label_id==3 ? 4 : a.permission_label_id.to_i
      end
      case auth_lvl
      when 7 #full access
        authorizations = ''
      when 6
        authorizations = 'PE + HD'
      when 5
        authorizations = 'PE + BD'
      when 4
        authorizations = 'PE'
      when 3
        authorizations = 'BD + HD'
      when 2
        authorizations = 'HD'
      when 1
        authorizations = 'BD'
      when 0
        authorizations = 'none'
      end
    end
    csv_line.push(authorizations)
  end
  csv_content.push(csv_line)
end

csv_content = csv_content.transpose
CSV.open(csv_file, 'w', {col_sep: ";", quote_char: '"', force_quotes: true}) do |csv|
  csv_content.each {|line| csv << line }
end