class BucketsController < ApplicationController
  before_action :require_login, only: [:get_upload_token]

  def get_upload_token_for_tzb
    data = {
      access_key_id: "HPUAGOFMTIZXHOASYVIZ",
      secret_access_key: "0dJhcHEj50nuC0TrX5ebNwwu0P2LgO9UCN79UMzB",
      server: "https://obs.cn-north-4.myhuaweicloud.com",
      bucket: "tzb2025-1"
    }
    token = encrypt(data.to_json)

    render_ok(data: token)
  end

  # 回调地址
  def callback
    Rails.logger.debug("##########buckets/callback/params:#{params}")

    if params[:container_type] == "TestSet"
      # 测试用例数据集
      data = params.except(*request.path_parameters.keys)
      render_ok(data: data)
    else
      render_ok(data: { attachment_url: attachment_url, attachment_id: attachment_id })
    end
  end

  private

  def encrypt(des_text)
    # des_text='{"access_key_id":"STS.NTuC9RVmWfJqj3JkcMzPnDf7X","access_key_secret":"E8NxRZWGNxxMfwgt5nFLnBFgg6AzgXCZkSNCyqygLuHM","end_point":"oss-accelerate.aliyuncs.com","security_token":"CAIS8gF1q6Ft5B2yfSjIr5fACIPmu7J20YiaaBX7j2MYdt9Cq6Ocujz2IHhMenVhA+8Wv/02n2hR7PcYlq9IS55VWEqc/VXLaywQo22beIPkl5Gfz95t0e+IewW6Dxr8w7WhAYHQR8/cffGAck3NkjQJr5LxaTSlWS7OU/TL8+kFCO4aRQ6ldzFLKc5LLw950q8gOGDWKOymP2yB4AOSLjIx6lAt2T8vs/7hmZPFukSFtjCglL9J/baWC4O/csxhMK14V9qIx+FsfsLDqnUIs0YWpf0p3P0doGyf54vMWUM05A6dduPS7txkLAJwerjVl1/ADxc0/hqAASXhPeiktbmDjwvnSn4iKcSGQ+xoQB468eHXNdvf13dUlbbE1+JhRi0pZIB2UCtN9oTsLHcwIHt+EJaoMd3+hGwPVmvHSXzECDFHylZ8l/pzTwlE/aCtZyVmI5cZEvmWu2xBa3GRbULo7lLvyeX1cHTVmVWf4Nk6D09PzTU8qlAj","bucket":"edu-bigfiles1","region":"oss-cn-hangzhou","callback_url":"https://data.educoder.net/api/buckets/callback.json","bucket_host":"data.educoder.net"}'
    # des = OpenSSL::Cipher::Cipher.new('aes-256-ctr')
    des = OpenSSL::Cipher.new('AES-256-CBC')
    des.encrypt
    # des.padding =
    des.key = 'bf3c199c2470cb477d907b1e0917c17b'
    des.iv = "5183666c72eec9e4"
    result = des.update(des_text)
    result << des.final
    Base64.strict_encode64 result

  end

  def build_upload_token(model_session, bucket)
    bucket_host = edu_setting('public_bucket_host')
    bucket_scheme = edu_setting('public_bucket_scheme')
    callback_url = "#{bucket_scheme}://#{bucket_host}/api/buckets/callback.json"
    @token = STS.client.assume_role(STS.role_arn, model_session)
    data = { access_key_id: @token.access_key_id, access_key_secret: @token.access_key_secret,
             end_point: OSS.end_point, security_token: @token.security_token, bucket: bucket, region: OSS.region,
             callback_url: callback_url, bucket_host: bucket_host }
    encrypt(data.to_json)
  end

end
