class SimManagement < ActiveRecord::Base
	# include Integer
	resourcify
  include RedisWrapper
  include PublicActivity::Model
  require 'json'
 
  belongs_to :organisation
  belongs_to :router_inventory
  has_many :purchase_order_items, as: :itemable
  has_many :purchase_orders, :through => :purchase_order_items
  belongs_to :sim_rate_plan
  #after_save :create_sim_rate_plan
  #validates :iccid, uniqueness: { case_sensitive: false }
  validates :iccid, presence: true, uniqueness: true

  tracked owner: ->(controller, model) { controller && controller.tracked_current_user },params:
  { :attributes => proc {|controller, model_instance| {"sim_management(#{model_instance.mac_id})" => 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 is_super_sim?
    return false if self.iccid.blank?
    return self.iccid.to_s[2] == "8" ? true : false
  end
 
  def self.sim_type(iccid)
    return "https://wireless.twilio.com" if iccid.blank?
    return iccid.to_s[2] == "8" ? "https://supersim.twilio.com" : "https://wireless.twilio.com"
  end

  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.get_sim_plans
    uri = URI.parse("https://wireless.twilio.com/v1/RatePlans")
    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)
    res["rate_plans"]
  end


	def self.get_all_sims
    url = URI.parse("https://wireless.twilio.com/v1/Sims")
    http = Net::HTTP.new(url.host, url.port)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    http.ssl_version = :TLSv1_2
    request = Net::HTTP::Get.new(url.path)
    request["content-type"] = 'application/x-www-form-urlencoded'
    request.basic_auth("ACfde9cc4317aab2aa69c98bd92f4e9b68","0a69b38638642946898f3125c35972e3")
    request["cache-control"] = 'no-cache'
    response = http.request(request)
    puts JSON.parse(response.body)
    @response = JSON.parse(response.body)
  end

  def self.get_sim_by_iccid(iccid)
    url = URI.parse(self.sim_type(iccid) + "/v1/Sims?Iccid=#{iccid}")
    http = Net::HTTP.new(url.host, url.port)
    http.use_ssl = true
    http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    http.ssl_version = :TLSv1_2
    request = Net::HTTP::Get.new(url)
    request["content-type"] = 'application/x-www-form-urlencoded'
    request.basic_auth("ACfde9cc4317aab2aa69c98bd92f4e9b68","0a69b38638642946898f3125c35972e3")
    request["cache-control"] = 'no-cache'
    response = http.request(request)
    puts JSON.parse(response.body)
    @response = JSON.parse(response.body)
  end

  def self.download_csv
    CSV.generate do |csv|
      csv << download_csv_header
      SimManagement.all.each do |sim_management|
        csv_column = []
        csv_column << sim_management.organisation.try(:organisation_name)
        user = sim_management.organisation.try(:users).try(:where,{role_id: Role.where(name:"admin").first.id}).try(:first)
        csv_column << user.try(:full_name)
        csv_column << sim_management.router_inventory.try(:mac_id)
        csv_column << "'#{sim_management.iccid}'"
        csv_column << sim_management.sid
        csv_column << sim_management.activated_on
        csv_column << sim_management.is_active
        csv_column << sim_management.auto_recharge
        csv_column << sim_management.created_at
        purchase_order = sim_management.purchase_orders.where(payment_status: "paid").last
        csv_column << purchase_order.try(:sim_rate_plan).try(:plan_description)
        csv_column << purchase_order.try(:sim_rate_plan).try(:plan_id)
        csv_column << purchase_order.try(:sim_rate_plan).try(:plan_type)
        csv_column << purchase_order.try(:sim_rate_plan).try(:data_plan)
        payment_invoice = purchase_order.try(:payment_invoices).try(:where,{payment_status: "success"}).try(:last)
        csv_column << payment_invoice.try(:invoiced_on)
        csv_column << payment_invoice.try(:invoice_number)
        csv_column << payment_invoice.try(:amount)
        csv_column << payment_invoice.try(:transcation_id)
        csv_column << payment_invoice.try(:customer_id)
        csv_column << payment_invoice.try(:customer_email)
        csv << csv_column
      end
    end
  end

  def self.download_csv_header
    ["Organisation Name","User Name","MAC ID", "ICC ID","SID", "Activated On", "Is Active", "Auto Recharge", "Created At", "Plan Description", "Plan Id","Plan Type", "Data Plan", "Invoiced On","Invoice Number","Amount","Transcation Id","Customer Id", "Customer Email"]
  end


  # def create_sim_rate_plan
  #   url = URI.parse("https://wireless.twilio.com/v1/RatePlans")
  #   http = Net::HTTP.new(url.host, url.port)
  #   http.use_ssl = true
  #   http.verify_mode = OpenSSL::SSL::VERIFY_NONE
  #   http.ssl_version = :TLSv1_2
  #   request = Net::HTTP::Post.new(url.path)
  #   valid_parameters = {unique_name: 'SmartMeterCA',
  #                       friendly_name: 'California SmartMeter Plan',
  #                       data_limit: 5,
  #                         messaging_enabled: true}

  #   request.body = valid_parameters
    
  #   request["content-type"] = 'application/x-www-form-urlencoded'
  #   request.basic_auth(APPLICATION['defaults']['twilio_sid'],APPLICATION['defaults']['twilio_token'])
  #   request["cache-control"] = 'no-cache'
  #   response = http.request(request)
  #   puts JSON.parse(response.body)
  #   return JSON.parse(response.body)
  # end 
 
end
