class InstallationsController < ApplicationController
  include RegisterHelper
  before_action :require_login

  # app详情
  def app
    @bot = Bot.find_by(uid: current_user.id)
  end

  def index
    @install_bots = BotInstall.where(bot_id: get_bot_id).group(:installer_id)
  end

  def show
    @install_bot = BotInstall.find_by(bot_id: get_bot_id, installer_id: params[:id]) || BotInstall.find_by(id: params[:id])
    tip_exception "参数installer_id错误"  if @install_bot.blank?
  end

  def repositories
    # 与github差异，所以取安装用户和bot对应所有的仓库
    # 必须使用access_tokens获取到bot的token才能查询
    tip_exception "无效Token" if current_user.platform != "bot"
    bot = Bot.find_by(uid: current_user.id)
    @install_bots = BotInstall.where(bot_id: bot.id).where(installer_id: params[:id])
  end

  def update_secret
    ActiveRecord::Base.transaction do
      bot = Bot.find params[:id]
      application = Doorkeeper::Application.find_by(uid: bot.client_id, secret: bot.client_secret)
      bot.client_secret = Doorkeeper::OAuth::Helpers::UniqueToken.generate
      bot.save!
      application.secret = bot.client_secret
      application.save!
      render_ok
    end
  end

  def update_private_key
    bot = Bot.find params[:id]
    bot.private_key = OpenSSL::PKey::RSA::generate(2048).to_s
    bot.save!
    render_ok
  end

  # 同步bot信息，回调地址和名称
  def update_callback_url
    bot = Bot.find params[:id]
    application = Doorkeeper::Application.find_by(uid: bot.client_id, secret: bot.client_secret)
    application.redirect_uri = bot.oauth_callback_url
    application.name = bot.name
    if bot.uid.present?
      bot_user = User.find_by(id: bot.uid)
      bot_user.update_column(:nickname, bot.name) if bot_user.present?
    end
    application.save
    render_ok
  end

  def suspended
    @install_bot = BotInstall.find params[:id]
    @install_bot.update_attributes!(state: 0)
    render_ok
  end

  def unsuspended
    @install_bot = BotInstall.find params[:id]
    @install_bot.update_attributes!(state: 1)
    render_ok
  end

  def auth_active
    begin
      @bot = Bot.find params[:id]
      tip_exception("该Bot已激活") if Doorkeeper::Application.find_by(uid: @bot.client_id, secret: @bot.client_secret).present?
      @bot.client_id = SecureRandom.uuid.gsub("-", "") if params[:client_id].blank?
      @bot.client_secret = Doorkeeper::OAuth::Helpers::UniqueToken.generate if params[:client_secret].blank?
      @bot.private_key = OpenSSL::PKey::RSA::generate(2048).to_s
      @bot.owner_id = current_user.id
      ActiveRecord::Base.transaction do
        # 注册bot对应oauth应用
        Doorkeeper::Application.create!(name: @bot.name, uid: @bot.client_id, secret: @bot.client_secret, redirect_uri: @bot.oauth_callback_url)
        # 注册bot对应用户
        result = autologin_register(User.generate_user_login('b'), nil, "#{SecureRandom.hex(6)}", 'bot', nil, @bot.name)
        tip_exception(-1, result[:message]) if result[:message].present?
        @bot.uid = result[:user][:id]
        @bot.save
        render_ok
      end
    rescue Exception => e
      tip_exception(-1, e.message)
    end
  end

  def access_tokens
    @install_bot = BotInstall.find_by(bot_id: get_bot_id, installer_id: params[:id]) || BotInstall.find_by(id: params[:id])
    tip_exception "参数installer_id错误"  if @install_bot.blank?
    @bot = @install_bot.bot
    @application = Doorkeeper::Application.find_by(uid: @bot.client_id, secret: @bot.client_secret)
    tip_exception("该Bot未激活") if @application.blank?
    # 给bot生成token，因为bot是机器人操作
    @access_token = Doorkeeper::AccessToken.create!({ :application_id => @application.id,
                                                      :resource_owner_id => @bot.uid,
                                                      :scopes => "public write",
                                                      :expires_in => "2592000",
                                                      :use_refresh_token => true
                                                    })
    @install_bot.update_attributes!(state: 1)
    render_ok(token: @access_token.token)
  end

  private

  def get_bot_id
    header = request.authorization
    pattern = /^Bearer /i
    token = header.gsub(pattern, "")
    decoded_token = JWT.decode token, nil, false
    # 前面已验证token有效期和正确性
    decoded_token[0]["iss"]
  rescue JWT::DecodeError
    Rails.logger.error "jwt token decode error:#{token}"
    tip_exception("无效Token")
  end

end

