class BatchLineItem < ApplicationRecord
	belongs_to :batch 	 
	attr_accessor :secret_token 
	attr_accessor :location 
  attr_accessor :product_type 
  require 'digest/md5'


  CARD = "Card"
  WRISTBAND = "Wristband"
  ACCOUNT_CARD = "Account Card"
    
 	def self.generate_account_no(location_code)
		 super_merchant = "101"
		 account_type='1'
		 location=location_code

  		o = [('0'..'9')].map { |i| i.to_a }.flatten
  		random_account_no = (0...9).map { o[rand(o.length)] }.join

  		account_no = super_merchant+account_type+location+random_account_no
  		find_account_no = BatchLineItem.find_by_asset_identity(account_no)
  		if !find_account_no.nil?		 
    			o = [('0'..'9')].map { |i| i.to_a }.flatten
    			random_account_no = (0...9).map { o[rand(o.length)] }.join
    			account_no = super_merchant+account_type+location+random_account_no		
		  end
		return account_no 
  end
  def self.generate_security_code

      o = [('0'..'8')].map { |i| i.to_a }.flatten
      security_code = (0...8).map { o[rand(o.length)] }.join

      find_account_no = BatchLineItem.find_by_security_code(security_code)
      if !find_account_no.nil?     
          o = [('0'..'8')].map { |i| i.to_a }.flatten
          security_code = (0...8).map { o[rand(o.length)] }.join      
      end
    return security_code 
  end
  def self.generate_barcode

      # o = [('0'..'9')].map { |i| i.to_a }.flatten
      # barcode = (0...8).map { o[rand(o.length)] }.join
      barcode= rand(1_000_000_0..9_999_999_9)
      find_account_no = BatchLineItem.find_by_barcode(barcode)
      if !find_account_no.nil?  
          # o = [('0'..'9')].map { |i| i.to_a }.flatten
          # barcode = (0...8).map { o[rand(o.length)] }.join  
          barcode = rand(1_000_000_0..9_999_999_9)    
      end
    return barcode 
  end
  def self.generate_serial_no(client_id)
	    find_lookup=Lookup.find_by_name('generate_serial_no')
	    if !find_lookup.nil?
  	    	max_value=find_lookup.max_value
  	    	max_value=max_value +1
  	    	prefix=find_lookup.prefix
  	    	max_length=find_lookup.max_length	    	
  	    	sufix_len=max_length-prefix.length 
  	    	sufix_str="0" * sufix_len	      
  	    	value_len= max_value.to_s.length	 
  	    	
          start=0
  	    	ends=sufix_len-value_len-1
  	    	sufix_str= sufix_str[start..ends]

          prefix_len=prefix.to_s.length
          client_len= client_id.to_s.length
          ends= prefix_len -client_len -1          
  	    	prefix=prefix[start..ends]

  	    	prefix_str=prefix.to_s + client_id.to_s

  	    	serial_no=prefix_str.to_s+sufix_str+max_value.to_s	    	
  	    	return serial_no	
  	   end
	end
	def self.to_csv(client_id,location_code)
		encrypt_key=""
		
		find_client=Client.find_by_id(client_id)		 
      if !find_client.nil?
          encrypt_key=find_client.secrect_key                     
      end
	    attributes = %w{serial_no asset_identity batch_id manufacture_uid asset_type secret_token  location}
	    CSV.generate(headers: true) do |csv|
	        csv << attributes     
	        all.each do |encoder|     
            if encoder.product_type_id ==1  
             
              str="account_no="+encoder.asset_identity.to_s+"&manufacture_uid="+encoder.manufacture_uid.to_s+"&serial_no="+encoder.serial_no.to_s 
              
            elsif encoder.product_type_id == 3
             
              attributes = attributes+ %w{security_code}
              str="account_no="+encoder.asset_identity.to_s+"&manufacture_uid="+encoder.manufacture_uid.to_s+"&serial_no="+encoder.serial_no.to_s+"&security_code="+encoder.security_code.to_s
            else              
              str="manufacture_uid="+encoder.manufacture_uid.to_s+"&serial_no="+encoder.serial_no.to_s 
            end      	 

	        	encryptd_data=BatchLineItem.encrypted(str,encrypt_key)	         
	          encoder.secret_token=encryptd_data
	          encoder.location=location_code  
	        	csv << attributes.map{ |attr| encoder.send(attr)}
	      	end
	    end
  	end

    def self.to_csv_seller(client_id,location_code)
    encrypt_key=""
    
    find_client=Client.find_by_id(client_id)     
      if !find_client.nil?
          encrypt_key=find_client.secrect_key                     
      end
      attributes = %w{serial_no asset_identity batch_id manufacture_uid asset_type secret_token  location barcode}
      CSV.generate(headers: true) do |csv|
          csv << attributes     
          all.each do |encoder|     
            if encoder.product_type_id ==1  
             
              str="account_no="+encoder.asset_identity.to_s+"&manufacture_uid="+encoder.manufacture_uid.to_s+"&serial_no="+encoder.serial_no.to_s 
              
            elsif encoder.product_type_id == 3
             
              attributes = attributes+ %w{security_code}
              str="account_no="+encoder.asset_identity.to_s+"&manufacture_uid="+encoder.manufacture_uid.to_s+"&serial_no="+encoder.serial_no.to_s+"&security_code="+encoder.security_code.to_s
            else              
              str="manufacture_uid="+encoder.manufacture_uid.to_s+"&serial_no="+encoder.serial_no.to_s+"&barcode="+encoder.barcode.to_s
            end        

            encryptd_data=BatchLineItem.encrypted(str,encrypt_key)           
            encoder.secret_token=encryptd_data
            encoder.location=location_code  
            csv << attributes.map{ |attr| encoder.send(attr)}
          end
      end
    end
  	def self.encrypted(message,encrypt_key)  
  		cipher = OpenSSL::Cipher::Cipher.new("aes-128-cbc")
  		cipher.encrypt

  		key = Digest::SHA1.hexdigest(encrypt_key)
  		iv =encrypt_key

  		cipher.key = encrypt_key
  		cipher.iv = encrypt_key

  		encrypted = cipher.update(message)
  		encrypted << cipher.final

  		encrypted=Base64.encode64(encrypted)

  		return encrypted 
  	end
    def self.create_product(asset_identity,serial_no,batch_id,manufacture_uid,card_type,security_code=nil)
        batchLineItem=BatchLineItem.new
        batchLineItem.asset_identity=asset_identity
        batchLineItem.serial_no=serial_no
        batchLineItem.batch_id=batch_id
        batchLineItem.manufacture_uid = manufacture_uid
        batchLineItem.asset_type = card_type
        batchLineItem.encoded_at = DateTime.now.beginning_of_day.utc.to_time.strftime("%Y-%m-%d")
        batchLineItem.verified_at =DateTime.now.beginning_of_day.utc.to_time.strftime("%Y-%m-%d")
        if !security_code.nil?
          batchLineItem.security_code = security_code
        end
        batch=Batch.find_by_id(batch_id)

        if batchLineItem.save
            lookup=Lookup.find_by_name('generate_serial_no')
            max_serail_no=lookup.max_value
            lookup.max_value=max_serail_no.to_i+1
            lookup.save
            
            card_qty=batch.qty_processing.to_i
            success_qty=batch.qty_success

            batch.qty_processing=card_qty+1
            batch.qty_success=success_qty+1
            batch.save

            @result = true,batchLineItem.serial_no,batchLineItem.asset_identity
        else
           qty_fail=batch.qty_fail
           batch.qty_fail=qty_fail+1
           batch.save

           @result=false,'Error occurs in registration encoder!'
        end 
    end   
    def self.get_array
    	arr=Array.new    	
    	(1..100).each do |i|
    		str= SecureRandom.hex    
    		uid=str[0..13]       
    		arr.push(uid)
    	end  
      @arr=arr    	 
    end     
end
