class Api::V1::SonarqubesController < Api::V1::BaseController
  before_action :load_repository
  include Repository::LanguagesPercentagable
  include SonarService

  def sonar_initialize
    gitea_params = { has_actions: params[:has_actions] == 'true' ? true :false }
    gitea_setting = Gitea::Repository::UpdateService.call(@owner, @project.identifier, gitea_params)
    if gitea_setting['has_actions'] == true
      Gitea::Repository::ActionSecretsService.new(@owner, @project.identifier, 'SONAR_HOST_URL', Rails.application.config_for(:configuration)['sonarqube']['url'] ).call
      Gitea::Repository::ActionSecretsService.new(@owner, @project.identifier, 'SONAR_TOKEN', Rails.application.config_for(:configuration)['sonarqube']['secret'] ).call
    else
      Gitea::Repository::ActionSecretsService.new(@owner, @project.identifier, 'SONAR_HOST_URL', Rails.application.config_for(:configuration)['sonarqube']['url'] ).destroy
      Gitea::Repository::ActionSecretsService.new(@owner, @project.identifier, 'SONAR_TOKEN', Rails.application.config_for(:configuration)['sonarqube']['secret'] ).destroy
    end
    @project.update(gitea_params)
    render_ok
  end

  def insert_file
    checkout_url = 'https://gitlink.org.cn/KingChan/checkout@v4'
    scanner_url = 'https://gitlink.org.cn/KingChan/sonarqube-scan-action@master'
    doxygen_url = "https://gitlink.gitlink.net"
    begin
      config = Rails.application.config_for(:configuration)
      sonarqube_config = config.dig('sonarqube')

      if sonarqube_config.present? && sonarqube_config['checkout'].present?
        checkout_url = sonarqube_config['checkout']
      end
      if sonarqube_config.present? && sonarqube_config['scanner'].present?
        scanner_url = sonarqube_config['scanner']
      end
      if sonarqube_config.present? && sonarqube_config['doxygen'].present?
        doxygen_url = sonarqube_config['doxygen']
      end
      raise 'sonar config missing' if sonarqube_config.blank?
    rescue => ex
      raise ex if Rails.env.production?

      puts %Q{\033[33m [warning] soanrqube config or configuration.yml missing,
           please add it or execute 'cp config/configuration.yml.example config/configuration.yml' \033[0m}
    end
    sonar_content = build_sonar_content(params[:owner], @project.id, languages_precentagable.keys)
    sonar_scanner_content = {
      filepath: '.gitea/workflows/SonarScanner.yaml',
      branch: params[:branch],
      new_branch: nil,
      content: "
              name: Sonar Scanner
              jobs:
                sonarqube:
                  runs-on: ubuntu-latest
                  steps:
                  - uses: #{checkout_url}
                    with:
                      # Disabling shallow clones is recommended for improving the relevancy of reporting
                      fetch-depth: 1
                      single-branch: true
                  - name: curl doxygen
                    run: |
                      curl -X GET #{doxygen_url}/generate?repo=#{@project.repository.url}

                  - name: new properties
                    run: |
                      cat <<EOF > sonar-project.properties
                      #{sonar_content}
                      EOF

                  - name: new build_tmp_folder
                    run: |
                      mkdir build_tmp_folder

                  - name: SonarQube Scan
                    uses:  #{scanner_url}
                    env:
                      SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
                      SONAR_HOST_URL:  ${{ secrets.SONAR_HOST_URL }}
       ",
      message: 'Add .gitea/workflows/SonarScanner.yaml',
      committer: {
        email: @owner.mail,
        name: @owner.login
      },
      identifier: @project.identifier
    }
    @path = GiteaService.gitea_config[:domain]+"/#{@project.owner.login}/#{@project.identifier}/raw/branch/#{params[:branch]}/"
    sonar_scanner_exit = Repositories::EntriesInteractor.call(@owner, @project.identifier, '.gitea/workflows/SonarScanner.yaml', ref: params[:branch])
    if sonar_scanner_exit.success?
      Gitea::UpdateFileInteractor.call(@owner.gitea_token, @owner.login, sonar_scanner_content.merge(sha:sonar_scanner_exit.result['sha']))
    else
      sonar_scanner_content[:content] = Base64.strict_encode64(sonar_scanner_content[:content])
      Gitea::CreateFileInteractor.call(@owner.gitea_token, @owner.login, sonar_scanner_content)
    end
    $gitea_hat_client.post_repos_actions_runs_by_owner_repo(@project&.owner&.login, @project&.identifier, {query: {workflow: "SonarScanner.yaml", ref: params[:branch]}})
    render_ok
  end

  def issues_search
    params_data = {
      components: "#{params[:owner]}-#{@project.id}",
      s: params[:s],
      impactSoftwareQualities: params[:impactSoftwareQualities],
      issueStatuses: params[:issueStatuses],
      ps:  params[:ps],
      p:  params[:p],
      facets: params[:facets],
      additionalFields: params[:additionalFields],
      timeZone: params[:timeZone],
      types: params[:types],
      impactSeverities: params[:impactSeverities],
      tags: params[:tags]
    }
    data = Sonarqube.client.get('/api/issues/search', query: params_data)
    render_ok data
  end

  def ce_component
    params_data = {
      components:  "#{params[:owner]}-#{@project.id}",
    }
    data = Sonarqube.client.get('/api/ce/component', query: params_data)
    render_ok data
  end

  def sources_issue_snippet
    params_data = {
      issueKey: params[:issueKey]
    }
    data = Sonarqube.client.get('/api/sources/issue_snippets', query: params_data)
    render_ok data
  end

  def rules_show
    params_data = {
      key: params[:key]
    }
    data = Sonarqube.client.get('/api/rules/show', query: params_data)
    render_ok data
  end

  def  doxygen_url
    config = Rails.application.config_for(:configuration)
    sonarqube_config = config.dig('sonarqube')
    doxygen_url = sonarqube_config['doxygen']
    data = {doxygen_url:  "#{doxygen_url}/files/#{@project.owner.login}/#{@project.identifier}/html/"}
    render_ok data
  end

  def analyze_doxygen
    config = Rails.application.config_for(:configuration)
    sonarqube_config = config.dig('sonarqube')
    doxygen_url = sonarqube_config['doxygen']

    url = "#{doxygen_url}/files/#{@project.owner.login}/#{@project.identifier}/html/analyze_doxygen.json"
    uri = URI.parse(url)
    response = Net::HTTP.get_response(uri)
    if response.code.to_i != 200
      puts "======= 接口请求失败！"
      data = { data: nil, msg: '文件不存在' }
    else
      data = { data: JSON.parse(response.body), msg: 'ok' }
    end
    render_ok data
  end

  def measures_search_history
    params_data = {
      from: params[:form],
      component: "#{params[:owner]}-#{@project.id}",
      metrics: params[:metrics],
      ps: params[:ps]
    }
    data = Sonarqube.client.get('/api/measures/search_history', query: params_data)
    render_ok data
  end

  def measures_component
    params_data = {
      component: "#{params[:owner]}-#{@project.id}",
      additionalFields: params[:additionalFields],
      metricKeys: params[:metricKeys]
    }
    data = Sonarqube.client.get('/api/measures/component', query: params_data)
    render_ok data
  end
end
