module ReportsService
    class CardComparisons

        def initialize(pl_plan_key, member_pb_entity_key = nil)
            @pl_plan_key = pl_plan_key
            @member_pb_entity_key = member_pb_entity_key
            @hlid_ids_compared = []
        end

        def call
            if @member_pb_entity_key
                IdCard::PrintData.where(primary_mb_member_key: @member_pb_entity_key).destroy_all
                CallStoredProc.new('HLQueueIDCardByKey', { PBEntityKey: @member_pb_entity_key }).call
                IdCardPrinterService::CardDataFormatter.new([{pl_plan_key: @pl_plan_key, member_keys: [@member_pb_entity_key]}]).call
                puts "use ID Cards app for group #{@pl_plan_key}, then press enter."
                continue = gets

                compare_member_cards(@member_pb_entity_key)
            else
                employer_card_comparison = Report::CardComparison.find_or_create_by(member_number: "#{@pl_plan_key}-Group", pl_plan_key: @pl_plan_key)

                AutomationService::EmployerMembersUpdate.new(@pl_plan_key).call
                employer_member_keys = Employer.find_by(pl_plan_key: @pl_plan_key).employer_member_keys
                IdCard::PrintData.where(pl_plan_key:  @pl_plan_key).destroy_all
                CallStoredProc.new('HLQueueAllIDCardsByPlan', { PLPlanKey: @pl_plan_key }).call
                IdCardPrinterService::CardDataFormatter.new(employer_member_keys).call

                puts "use ID Cards app for group #{@pl_plan_key}, then press enter."
                continue = gets

                IdCard::PrintData.where(pl_plan_key: @pl_plan_key, primary_mb_member_key: nil).destroy_all


                # new_cards = IdCard::PrintData.where(pl_plan_key: @pl_plan_key)
                # add_dependent_cards(new_cards)
                new_card_member_keys = IdCard::PrintData.where(pl_plan_key: @pl_plan_key).pluck(:primary_mb_member_key).uniq
                old_card_member_keys = Vhcs::HlidCardEggData.where(pl_plan_key: @pl_plan_key).pluck(:primary_mb_member_key).uniq.map(&:to_s)

                missing_from_new = old_card_member_keys - new_card_member_keys
                missing_from_old = new_card_member_keys - old_card_member_keys

                if missing_from_new.present? || missing_from_old.present?
                    employer_card_comparison.comparison_errors.new(
                        card_field: "Missing Cards", 
                        new_value: missing_from_old.join(', '), 
                        old_value: missing_from_new.join(', ')
                    )
                end

                # group_errors = []
                # unless new_card_count == old_card_count
                #     group_errors.push({
                #             employer: @pl_plan_key,
                #             field: 'Card Count Mismatch',
                #             new_value: new_card_count,
                #             old_value: old_card_count
                #         })
                # end
                member_keys_array = new_card_member_keys | old_card_member_keys
                member_keys_array.each do |member_key|
                    compare_member_cards(member_key)
                end

                failed_cards = Report::CardComparison.where(pl_plan_key: @pl_plan_key, passed: false).where.not(member_number: @pl_plan_key)
                if failed_cards.empty?
                    employer_card_comparison.passed = true
                end

                employer_card_comparison.save
                @hlid_ids_compared
            end
            
        end

        private

        def compare_member_cards(member_pb_entity_key)
            member_card_comparison = Report::CardComparison.find_or_create_by(member_number: member_pb_entity_key, pl_plan_key: @pl_plan_key)
            new_card = IdCard::PrintData.find_by(primary_mb_member_key:  member_pb_entity_key)
            old_card = Vhcs::HlidCardEggData.where(primary_mb_member_key: member_pb_entity_key).first
            @hlid_ids_compared << old_card.id

            errors = []
            if new_card.present? && old_card.present?

                # :pl_plan_key, :primary_mb_member_key, :family_id, :full_name, :medical_eff_date, :dental_coverage,
                # :provider_line_1, :provider_line_2, :provider_line_3, :provider_line_4, :provider_line_5, :provider_line_6,
                #     :provider_line_7, :provider_line_8, :provider_line_9, :provider_line_10, :provider_line_11, :provider_line_12,
                #     :claim_to_1, :claim_to_2, :claim_to_3, :claim_to_4, :claim_to_5, :claim_to_6,
                #     :claim_to_7, :claim_to_8, :claim_to_9, :claim_to_10, :claim_to_11, :claim_to_12,
                #     :precert_1, :precert_2, :precert_3, :precert_4, :customer_service, :web_url, :dependent_1, :dependent_2, :dependent_3,
                #     :dependent_4, :dependent_5, :dependent_6, :dependent_7, :dependent_8, :benefit_desc_1, 

                new_card_common = new_card.attributes.with_indifferent_access.except(
                    :id, :created_at, :full_name_last_name_first, :network_provider, :plan_id, 
                    :network_logo_filename, :employer_logo_filename, :sample_plan_title, :jasper_batch_id, :updated_at
                )
                new_card_common.delete_if { |key, value| key.match?(/[[:upper:]]/) }

                new_card_dependents = new_card.attributes.with_indifferent_access.slice(
                    :dependent_1, :dependent_2, :dependent_3, :dependent_4, :dependent_5, :dependent_6, :dependent_7, :dependent_8
                )
                new_card_dependents.delete_if { |key, value| key.match?(/[[:upper:]]/) }

                new_card_dental = new_card[:dental_coverage]
                new_card_eff_date = new_card[:medical_eff_date]

                # old_card_common = old_card.attributes.except(
                #     :id, :facility, :ssn, :medical_coverage, :dental_eff_date, :dental_group_num, :mail_to, :mail_to_2, :contact_line_1, 
                #     :contact_line_2, :contact_line_3, :group_number, :group_no, :help_desk, :expr_1, :line_3, :ppo_lookup_1, :ppo_lookup_2, 
                #     :precert_5, :precert_6, :misc_data, :ppo_data, :ppo_data_2, :ppo_data_3, :last_name, :card_type, :provider_code
                # )
                old_card_common = old_card.attributes.with_indifferent_access.slice(
                    :employer_name, :full_name, :group_number, :provider_line_1, :provider_line_2, :provider_line_3, 
                    :provider_line_4, :provider_line_5, :provider_line_6, :provider_line_7, :provider_line_8, :provider_line_9, :provider_line_10, 
                    :provider_line_11, :claim_to_1, :claim_to_2, :claim_to_3, :claim_to_4, :claim_to_5, :claim_to_6, :claim_to_7, :claim_to_8, :claim_to_9, 
                    :claim_to_10, :claim_to_11, :family_id, :rx_group, :customer_service, :web_url, :benefit_desc_1, :benefit_1, :benefit_desc_2, :benefit_2, :benefit_desc_3, :benefit_3, 
                    :benefit_desc_4, :benefit_4, :benefit_desc_5, :benefit_5, :benefit_desc_6, :benefit_6, :benefit_desc_7, :benefit_7, :benefit_desc_8, :benefit_8, 
                    :benefit_desc_9, :benefit_9, :benefit_desc_10, :benefit_10, :benefit_desc_11, :benefit_11, :benefit_desc_12, :benefit_12, :benefit_desc_13, :benefit_13, 
                    :benefit_desc_14, :benefit_14, :pl_plan_key, :primary_mb_member_key, :provider_line_12, :claim_to_12
                )   # :precert_1, :precert_2, :precert_3, :precert_4
                old_card_common.transform_keys!(division: :employer_name, medical_group_num: :group_number, rx_group_id: :rx_group)

                old_card_dependents = old_card.attributes.with_indifferent_access.slice(
                    :dependent_1, :dependent_2, :dependent_3, :dependent_4, :dependent_5, :dependent_6, :dependent_7, :dependent_8
                )
                old_card_dependents.delete_if { |key, value| key.match?(/[[:upper:]]/) }

                old_card_dental = old_card[:dental_coverage]
                old_card_eff_date = old_card[:medical_eff_date]

                old_card_common.each do |key, value|
                    # if key == :benefit_desc_4
                    #     binding.pry
                    # end
                    unless new_card_common[key].to_s.downcase.strip.gsub(/\W/, ' ') == value.to_s.downcase.strip.gsub(/\W/, ' ')
                        comp_error = member_card_comparison.comparison_errors.find_or_create_by(card_field: key.to_s)
                        comp_error.update!(new_value: new_card_common[key], old_value: value)
                        # errors.push({
                        #     member: old_card_common[:primary_mb_member_key],
                        #     field: key,
                        #     new_value: value,
                        #     old_value: new_card_common[key]
                        # })
                    end
                end

                unless old_card_dependents.values.sort == new_card_dependents.values.sort

                    missing_from_new = (old_card_dependents.values - new_card_dependents.values).compact_blank
                    missing_from_old = (new_card_dependents.values - old_card_dependents.values).compact_blank

                    # member_card_comparison.comparison_errors.new(
                    #     card_field: "Missing Dependent(s)", 
                    #     new_value: missing_from_old.join(', '), 
                    #     old_value: missing_from_new.join(', ')
                    # )

                    comp_error = member_card_comparison.comparison_errors.find_or_create_by(card_field: "Missing Dependent(s)")
                    comp_error.update!(new_value: missing_from_old.join(', '), old_value: missing_from_new.join(', '))

                    # errors.push({
                    #         member: old_card_common[:primary_mb_member_key],
                    #         field: 'Missing Dependent(s)',
                    #         new_value: new_card_dependents.values,
                    #         old_value: old_card_dependents.values
                    #     })
                end

                unless new_card_dental == old_card_dental || (old_card_dental == "NONE" && new_card_dental.empty?)
                    member_card_comparison.comparison_errors.new(
                        card_field: "dental_coverage", 
                        new_value: new_card_dental, 
                        old_value: old_card_dental
                    )

                    comp_error = member_card_comparison.comparison_errors.find_or_create_by(card_field: "dental_coverage")
                    comp_error.update!(new_value: new_card_dental, old_value: old_card_dental)

                    # errors.push({
                    #         member: old_card_common[:primary_mb_member_key],
                    #         field: :dental_coverage,
                    #         new_value: new_card_dental,
                    #         old_value: old_card_dental
                    #     })
                end

                unless new_card_eff_date.to_date == old_card_eff_date.to_date
                    # member_card_comparison.comparison_errors.new(
                    #     card_field: "medical_eff_date", 
                    #     new_value: new_card_eff_date, 
                    #     old_value: old_card_eff_date
                    # )

                    comp_error = member_card_comparison.comparison_errors.find_or_create_by(card_field: "medical_eff_date")
                    comp_error.update!(new_value: new_card_eff_date, old_value: old_card_eff_date)

                    # errors.push({
                    #         member: old_card_common[:primary_mb_member_key],
                    #         field: :medical_eff_date,
                    #         new_value: new_card_eff_date,
                    #         old_value: old_card_eff_date
                    #     })
                end
            else
                comp_error = member_card_comparison.comparison_errors.find_or_create_by(card_field: "Missing Member")
                comp_error.update!(new_value: new_card.present?, old_value: old_card.present?)
                # member_card_comparison.comparison_errors.new(
                #     card_field: "Missing Member", 
                #     new_value: new_card.present?, 
                #     old_value: old_card.present?
                # )
                # errors.push({
                #     member: old_card[:primary_mb_member_key],
                #     field: "Missing Member",
                #     new_value: new_card.present?,
                #     old_value: old_card.present?
                # })
            end
            if member_card_comparison.comparison_errors.empty?
                member_card_comparison.passed = true
            end
            member_card_comparison.save
        end

        # def add_dependent_cards(batch)
        #     batch.where.not(dependent_1: [nil, ""]).find_each do |member_card|
        #         dependent_card = member_card.dup
        #         dependent_card.update(
        #             full_name_last_name_first: member_card.full_name_last_name_first.concat(" dependent")
        #         )
        #         dependent_card.save
        #     end
        # end
        
    end
end