# 执行示例 bundle exec rake "sync_mindspore:contributor_to_user"
# RAILS_ENV=production bundle exec rake "sync_mindspore:contributor_to_user"
desc "mindspore项目贡献者数据"

# 同步mindspre贡献者数据至用户表

namespace :sync_mindspore do
  desc "同步用户信息" 
  task contributor_to_user: :environment do 
    i = 1
    fail_users = []
    file = File.open('public/mindspore_authors', 'r')
    file.each_line do |l| 
      itemArray = l.gsub("\r\n", "").split("|:|")
      email = itemArray[0]
      username = itemArray[1]
      password = '12345678'
      puts "=======Generate:[#{i}] Username: #{username}, Password: #{password}, Email: #{email}======="
      puts "=======Create User Begin====== "

      user = User.new(admin: false, login: username, mail: email, type: "User", is_test: 1)
      user.password = password
      user.platform = 'forge'
      user.activate
      
      unless user.valid?
        puts "=======Create User Fail!====== "
        fail_users << [username, email]
        next 
      end

      interactor = Gitea::RegisterInteractor.call({username: username, email: email, password: password})
      if interactor.success?
        gitea_user = interactor.result
        result = Gitea::User::GenerateTokenService.call(username, password)
        user.gitea_token = result['sha1']
        user.gitea_uid = gitea_user[:body]['id']
        if user.save!
          UserExtension.create!(user_id: user.id)
        end
      end

      i += 1
      puts "=======Create User End====== "
    end
    
    puts "=======Fail Users:#{fail_users}====== "

    file.close
  end
  # 执行示例 bundle exec rake "sync_mindspore:init_project_blockchain[1,2]"
  # RAILS_ENV=production bundle exec rake "sync_mindspore:init_project_blockchain[1,2]"
  desc "初始化区块链项目"
  task :init_project_blockchain, [:id, :init_id] => :environment do |t, args|
    puts "=====Init Project Blockchain: #{args.id}====="
    project = Project.find_by_id(args.id)
    project.update_column(:use_blockchain, true)
    
    username = project.user_id.to_s
    token_name = project.id.to_s
    total_supply = 10000
    token_balance = [[init_id.to_s, 100]]

    contributions = Project.mindspore_contributors
    total_contributions = contributions.sum{|i| i["contributions"]}
    contributions.each do |con|
      cont_balance = Float(con["contributions"]*9900/total_contributions).round(0)
      token_balance << [con["id"].to_s, cont_balance] if cont_balance > 0
    end
    params = {
      "request-type": "create repo",
      "username": username,
      "token_name": token_name,
      "total_supply": total_supply,
      "token_balance": token_balance
    }.to_json
    resp_body = Blockchain::InvokeBlockchainApi.call(params)
  end
end
