# frozen_string_literal: true
module Panel
  #
  class ExpedientsController < PanelController
    include Panel::Crud
    include Panel::Multiple

    def model
      Expedient
    end

    def permits
      [:received_at, :entry_way_id, :contact, :phone, :email, :comment,
       :institution_id, :gender, :age, :state_id, :city_id, :anonymous,
       :classification_type, :branch_id, :response, :happened_at,
       :place, :national_license_plate, :personnel_name, :process_name,
       tag_list: [] ]
    end

    def exportable_fields
      [:name]
    end

    def init_form
      @entry_ways   = EntryWay.where(institution_id: nil)
      unless current_user.one_institution?
        @institutions = Institution.accessible_by(current_ability).order(:name).select(:id, :name)
      end
      unless current_user.has_role?('admin')
        @entry_ways = @entry_ways.or(EntryWay.where(institution_id: current_user.institution_ids))
      end
      @entry_ways   = @entry_ways.order(:name)
      @branchs = Branch.where(institution_id: current_user.institution_ids)
      #@tags = ActsAsTaggableOn::Tag.for_context(:tags)
    end

    def show
      breadcrumbs_for(:show)
      @event = @item.events.new
      @event.start_at = Time.current
      @management     = @item.managements.new
      @managements    = @item.managements.reorder(created_at: :asc)
      @process_event  = @item.events.where(state: 'process').first
      if @item.redirected?
        # Find where
        @new_expedient  = Expedient.where(expedient_id: @item.id).first
        @redirect_event = @item.events.where(state: 'redirected').first
      end
      if @item.closed?
        @closed_info = @item.events.where(state: 'closed').first
      end
      @tags = ActsAsTaggableOn::Tag.for_context(:tags)
      respond_to do |format|
        format.html
        format.pdf do
          pdf = ExpedientPdf.new(@item, params[:managements])
          send_data pdf.render, filename: "Caso #{@item.code}", type: 'application/pdf', disposition: 'inline'
        end
      end
    end

    def redirect
      @item = Expedient.find params[:id]
      # TODO verify permissions to redirect this expedient
      data                   = params[:expedient]
      new_exp                = @item.dup
      new_exp.user_id        = current_user.id
      new_exp.institution_id = data[:institution_id]
      new_exp.expedient_id   = @item.id
      new_exp.branch_id = nil
      # new_exp.confirmed_at = Time.current
      # new_exp.admitted_at = Time.current
      new_exp.state = 'new'
      if new_exp.save
        # new_exp.set_correlative
        @item.assets.each do |asset|
          Asset.create attachment: asset.attachment, assetable: new_exp
        end
        # cerramos la solicitud como redireccionada
        @item.events.create user_id: current_user.id, state: 'redirected', justification: data[:justification], start_at: Time.current
      end
      redirect_to panel_expedient_url(@item) and return
    end

    #
    ## Overwrite

    def respond_to_json
      @q = model.accessible_by(current_ability, :read).ransack(params[:filter])
      @c = @q.result.paginate(page: params[:page], per_page: params[:count])

      render json: json_result(@c)
    end

    def set_item
      @item = if model.respond_to?(:friendly)
                model.friendly.find params[:id]
              else
                model.find params[:id]
              end
    end

    def new
      @item = model.new
      @item.received_at = Time.current

      init_form
      breadcrumbs_for(:new)
      render template: 'panel/expedients/form'
    end

    def create
      @item              = model.new item_params
      @item.confirmed_at = Time.current
      @item.user_id      = current_user.id
      set_uniq_institution! if current_user.one_institution?
      success            = @item.save
      respond_to do |format|
        format.html {
          if success
            return redirect_to(show_url, flash: {saved: true})
          else
            init_form
            breadcrumbs_for(:new)
            render template: 'panel/expedients/form'
          end
        }
        format.json {
          if success
            # Save assets
            if params[:file]
              params[:file].each do |k, file|
                Asset.create attachment: file, assetable: @item
              end
            end
            render json: {code: 200, item: @item, redirect_url: show_url}
          else
            render json: {code: 422, errors: @item.errors}
          end
        }
      end
    end

    def edit
      init_form
      breadcrumbs_for(:edit)

      render template: 'panel/expedients/form'
    end

    def update
      success = @item.update_attributes(item_params)
      respond_to do |format|
        format.html {
          if success
            return redirect_to(show_url, flash: {saved: true})
          else
            init_form
            breadcrumbs_for(:new)
            render template: 'panel/expedients/form'
          end
        }
        format.json {
          if success
            # Save assets
            if params[:file]
              params[:file].each do |k, file|
                Asset.create attachment: file, assetable: @item
              end
            end
            render json: {code: 200, item: @item, redirect_url: edit_url}
          else
            render json: {code: 422, errors: @item.errors}
          end
        }
      end
    end

    def documents
      require 'rubygems'
      require 'zip'
      expedient = Expedient.find(params[:id])
      documents = expedient.assets + \
        expedient.managements.map(&:assets).flatten + \
        Comment.where(management_id: expedient.management_ids).map(&:assets).flatten
      if documents.any?
        file_name = "Documentos-#{expedient.id}.zip"
        t = "#{Dir.tmpdir}/#{file_name}"
        FileUtils.rm_f(t)
        Zip::File.open(t, Zip::File::CREATE) do |zipfile|
          documents.each_with_index do |asset, i|
            zipfile.add("#{i + 1}.#{asset.attachment_file_name}", asset.attachment.path)
          end
        end
        send_file t, :type => 'application/zip',
                             :disposition => 'attachment',
                             :filename => "#{file_name}"
      else
        redirect_to panel_expedient_url(expedient) and return
      end
    end

    def tags
      expedient = Expedient.find(params[:id])
      begin
        expedient.tag_list = params[:expedient][:tag_list]
        expedient.save
      end
    end

    private
    def breadcrumbs_for(action)
      add_breadcrumb t('home'), panel_root_url
      add_breadcrumb humanized_model_name(count: :many), index_url
      add_breadcrumb @item.correlative || t(action.to_s), nil
    end

    def json_methods
      [ :state_s, :institution_name, :branch_name, :tags_string ]
    end
  end
end
