class Www::InformationRequestsController < WwwController

  before_filter :load_states, :load_occupations, :load_institutions, :build_breadcrumb, :applications_category
  include HTTParty
  require 'base64'

  def index
    ### requests
    requests = InformationRequest.confirmed.valid.includes(city: :state)
    requests = requests.where('information_requests.admitted_at > ?', Date.parse(params[:start_at]).beginning_of_day) if params[:start_at].present?
    requests = requests.where('information_requests.admitted_at < ?', Date.parse(params[:end_at]).end_of_day) if params[:end_at].present?
    @total_requests = requests.count
    @website_requests = requests.select{|r| r.from_website?}.size
    @manual_requests = requests.select{|r| !r.from_website?}.size
    ### requirements
    managements = Comment.requirements.where(commentable_type: 'InformationRequest', commentable_id: requests.pluck(:id))
    requirements = InformationRequestRequirement.where(comment_id: managements.pluck(:id))
    ### information type
    @informal = requirements.where(information_type: 'informal').pluck(:weight).sum
    @public = requirements.where(information_type: 'public').pluck(:weight).sum
    @reserved = requirements.where(information_type: 'reserved').pluck(:weight).sum
    @confidential = requirements.where(information_type: 'confidential').pluck(:weight).sum
    @non_existent = requirements.where(information_type: 'non_existent').pluck(:weight).sum
    @redirected = requirements.where(information_type: 're_routed').pluck(:weight).sum
    @undelivered = requirements.where(information_type: 'undelivered').pluck(:weight).sum
    @not_processed = requirements.where(information_type: 'not_processed').pluck(:weight).sum
    ### graphic resume
    @data_information_type = [ [t('admin.information_requests.statistics.information_type'), t('admin.information_requests.statistics.total')], [t('admin.information_requests.statistics.informal'), @informal], [t('admin.information_requests.statistics.public'), @public], [t('admin.information_requests.statistics.reserved'), @reserved], [t('admin.information_requests.statistics.confidential'), @confidential], [t('admin.information_requests.statistics.non_existent'), @non_existent], [t('admin.information_requests.statistics.redirected'), @redirected], [t('admin.information_requests.statistics.undelivered'), @undelivered], [t('admin.information_requests.statistics.not_processed'), @not_processed] ]
    ### graphic demography
    @title_gender = t('admin.information_requests.statistics.requests_by_gender')
    @data_gender = requests.group_by{|r| r.gender}.map{|k, v| [t("admin.information_requests.statistics.#{k.downcase}"), v.size] }
    @data_gender.unshift([t('admin.information_requests.statistics.gender'), t('admin.information_requests.statistics.total')])
    @title_person = t('admin.information_requests.statistics.requests_by_person_type')
    @data_person = requests.group_by{|r| r.entity_type}.map{|k, v| [t("admin.information_requests.statistics.#{k}"), v.size] }
    @data_person.unshift([t('admin.information_requests.statistics.person_type'), t('admin.information_requests.statistics.total')])
    @title_age = t('admin.information_requests.statistics.requests_by_age')
    @data_age = [ [t('admin.information_requests.statistics.age'), t('admin.information_requests.statistics.total')], [t('admin.information_requests.statistics.less_than_18'), requests.where('information_requests.age < 18').count], [t('admin.information_requests.statistics.between_18_and_30'), requests.where('information_requests.age BETWEEN 18 AND 30').count], [t('admin.information_requests.statistics.between_31_and_50'), requests.where('information_requests.age BETWEEN 31 AND 50').count], [t('admin.information_requests.statistics.greater_than_50'), requests.where('information_requests.age > 50').count] ]
    @title_department = t('admin.information_requests.statistics.requests_by_department')
    @data_department = requests.group_by{|r| (r.city.state.name rescue I18n.t('label.none'))}.sort_by{|k, v| k}.map{|k, v| [k, v.size] }
    @data_department.unshift([t('admin.information_requests.statistics.department'), t('admin.information_requests.statistics.total')])
  end

  def new
    @information_request = InformationRequest.new
    if params[:institution_id]
      @information_request.institution_id = params[:institution_id].to_i
    end
    @information_request.textcaptcha
  end

  def new2
  end

  def create

    @information_request = InformationRequest.new(params[:information_request])
    @information_request.notification_mode = params[:notification_mode] || []

    if @information_request.save

      @information_request.deliver_confirmation_email_request
      session[:information_request_id] = @information_request.id
      redirect_to please_confirm_www_information_requests_path

    else
      unless @information_request.state_id.blank?
        @cities = State.find(@information_request.state_id).cities.order(:name)
      end
      @information_request.textcaptcha
      render action: :new
    end
  end

  def create2
    request.format = :json

    #api_uri = "http://www.localhost.com:3000/api/information_requests.json"
    api_uri = "http://solicitudes.gobiernoabierto.gob.sv/api/information_requests.json"

    form                       = {}
    form[:information_request] = params[:information_request]
    form[:notification_mode]   = params[:notification_mode]

    # File uploads
    legal_representative_doc_file_upload = params[:information_request][:legal_representative_doc].tempfile rescue nil
    legal_representative_doc = nil
    if legal_representative_doc_file_upload
      legal_representative_doc  = "data:#{params[:information_request][:legal_representative_doc].content_type};base64,#{Base64.encode64(File.read(legal_representative_doc_file_upload))}"
      params[:information_request][:legal_representative_doc] = legal_representative_doc
    end

    document_front_image_file_upload = params[:information_request][:document_front_image].tempfile rescue nil
    document_front_image = nil
    if document_front_image_file_upload
      document_front_image  = "data:#{params[:information_request][:document_front_image].content_type};base64,#{Base64.encode64(File.read(document_front_image_file_upload))}"
      params[:information_request][:document_front_image] = document_front_image
    end

    document_back_image_file_upload = params[:information_request][:document_back_image].tempfile rescue nil
    document_back_image = nil
    if document_back_image_file_upload
      document_back_image  = "data:#{params[:information_request][:document_back_image].content_type};base64,#{Base64.encode64(File.read(document_back_image_file_upload))}"
      params[:information_request][:document_back_image] = document_back_image
    end

    request = HTTParty.post(api_uri, :body => form, :headers => {})
    #response = (post(Accounts.root_url+"/sobjects/Account/", :body => {:name => "graham"}.to_json) , :options => { :headers => { 'Content-Type' => 'application/json' } } )

    respond_to do |format|
      if !request.nil?
        if request.code == 200
          format.json { render :json => {}, :status => 200 }
          #redirect_to please_confirm_www_information_requests_url
        else
          format.json { render :json => request.parsed_response, :status => 422 }
        end
      else
        request = {}
        request[:error] = "Uh oh!"
        format.json { render :json => request, :status => 500 }
      end
    end
  end

  def please_confirm

    if session[:information_request_id]
      @information_request = InformationRequest.find(session[:information_request_id])
      session.delete :information_request_id
    else
      render_404
    end
  end

  def confirm
    @information_request = InformationRequest.find_by_valid_token(:confirm_email, params[:id])

    if @information_request
      #@information_request.set_reference_code
      #@information_request.set_correlative
      # state_id is required
      @information_request.state_id = @information_request.city.state.id rescue nil
      @information_request.confirmed = true
      @information_request.confirmed_at = Time.current
      @information_request.save
      @information_request.deliver_information_request
      #@information_request.deliver_information_request_user_create
      # Expire token
      @information_request.get_confirm_email_token.use!
    else
      render_404
    end
  end

  private

    def load_states
      @states = State.order(:name)
    end

    def load_occupations
      @occupations = Occupation.order(:name)
    end

    def load_institutions
      @institutions = Institution.where(at_information_requests: true).order(:name)
    end

    def build_breadcrumb
      add_breadcrumb I18n.t('www.layout.home'), www_root_path
      add_breadcrumb t('www.information_requests.new.title')
    end

    def nationalities
      @nationalities ||= Nationality.order(:name)
    end
    helper_method :nationalities

end
