class PurchaseOrder < ActiveRecord::Base

#Payment status will be "New" by default in purchase orders. 
#If the order got created the payment status changes to Payment processing
# If the Payment is success the PaymentStatus will changes to Paid else Not paid

  require 'json'
  include PublicActivity::Model
  belongs_to :organisation
  belongs_to :router_inventory
  has_many :purchase_order_items, :dependent => :destroy
  has_many :sim_managements, through: :purchase_order_items, source: :itemable_id, source_type: "SimManagement"
  has_one :sim_payment
  has_many :payment_invoices
  belongs_to :sim_rate_plan
  before_save :save_order_amount
  scope :completed, -> { where("payment_status != 'incomplete'") }
  
  tracked owner: ->(controller, model) { controller && controller.tracked_current_user },params:
  { :attributes => proc {|controller, model_instance| {"purchase_orders(#{model_instance.plan_description})" => model_instance.changes}}},organisation_id: ->(controller, model) { controller && controller.tracked_current_user.organisation_id },:location_network_id => nil

  tracked assumed_by: proc {|controller, model| controller.user_assumed_by if controller}

	def self.sim_usage
		uri = URI.parse("https://preview.twilio.com/wireless/Sims/DEc0bd47abcb834b15c30e1755c513cc84/Usage")
		http = Net::HTTP.new(uri.host, uri.port)
		http.use_ssl = true
		request = Net::HTTP::Get.new(uri.request_uri)
		request.basic_auth("ACfde9cc4317aab2aa69c98bd92f4e9b68", "0a69b38638642946898f3125c35972e3")
		response = http.request(request)
		res = JSON.parse(response.body)
		# @plans = res["data_usage"]["sent"]
		data = []
		res["data_usage"]["total"]
	end


	def self.grouped_collection_of_plan_name_type
    hash = {"Pooled" => [], "Individual" => []}
    @sim_rate_plan = SimRatePlan.all
    @sim_rate_plan.each do |sim|
    	if sim.plan_type == "POOLED"
   			hash["Pooled"] << ["#{sim.data_plan}", "#{sim.id}" ]
			else
				hash["Individual"] << ["#{sim.data_plan}", "#{sim.id}" ]
			end	
		end
    hash
  end


  def save_order_amount
    @sim_details  = SimRatePlan.where(id: self.sim_rate_plan_id)
    @total_amount = @sim_details.pluck(:amount).first.to_f * self.purchase_order_items.to_a.count
    self.amount = @total_amount
  end 


end
