class Api::V1::Projects::Sca::BaseService < ApplicationService
  private
  def base_url
    domain_url + Rails.application.config_for(:configuration)["sca"]["base_url"]
  end

  def domain_url
    Rails.application.config_for(:configuration)["sca"]["domain"]
  end

  def auth_token
    Rails.application.config_for(:configuration)["sca"]["token"]
  end

  def login_token
    params = {
      "username":  Rails.application.config_for(:configuration)["sca"]["username"],
      "password":  Rails.application.config_for(:configuration)["sca"]["password"]
    }
    sca_post_request("rest-auth/login/", params)
  end

  def sca_get_request(url, params = {} )
    begin
      uri = URI.parse(base_url + url)
      uri.query = URI.encode_www_form(params) if params && !params.empty?

      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = (uri.scheme == "https")

      request = Net::HTTP::Get.new(uri.request_uri)
      request["Content-Type"] = "application/json"
      request["Authorization"] = auth_token if auth_token

      response = http.request(request)

      {
        code: response.code.to_i,
        body: response.body,
        json: (JSON.parse(response.body) rescue nil)
      }
    rescue
      raise Error, "SCA服务器错误，请联系系统管理员！"
    end
  end

  def sca_post_request(url, params = {})
    begin
      uri = URI.parse(base_url + url)

      http = Net::HTTP.new(uri.host, uri.port)
      http.use_ssl = (uri.scheme == "https")

      request = Net::HTTP::Post.new(uri.request_uri)
      request["Content-Type"] = "application/json"
      request["Authorization"] = auth_token if auth_token
      request.body = params.to_json if params && !params.empty?

      response = http.request(request)

      {
        code: response.code.to_i,
        body: response.body,
        json: (JSON.parse(response.body) rescue nil)
      }
    rescue
      raise Error, "SCA服务器错误，请联系系统管理员！"
    end
  end


  def sca_user_info
    if Rails.cache.fetch("sca_user").nil?
      data = sca_get_request("user/", params = {})
      Rails.cache.write("sca_user",data[:body], expires_in: 1.day, force: true)
      data[:json]
    else
      JSON.parse Rails.cache.fetch("sca_user")
    end
  end

  def sca_team_id
    data = sca_get_request("orgs/#{sca_user_info["default_org"]}/teams/", params = {})
    default_team = data[:json]["results"].find { |team| team["is_default"] }
    default_team ? default_team["id"] : nil
  end

end