require 'yk_command/gitlab/yk_gitlab'
require 'yk_command/analyze/request'
require 'yk_command/config/yk_config'

module YkCommand

  GITLAB_CONFIG_FILE = '.YKGitlabConfig.yml'.freeze

  class ComponentManagePlatform < Thor
    include Thor::Actions
    no_commands do
      def initialize
        path = __dir__
        config = YkConfig.new path
        @gitlab_srvice = YkGitlab.new(config.read_config GITLAB_CONFIG_FILE)
        @api_service = Request.new(config.read_config SERVER_ENV_CONFIG_FILE)
      end

      def update_app_data
        data = @gitlab_srvice.get_all_app
        list = data.parsed_response['shared_projects']
        list.each do |project |
          committers = [];
          commits = @gitlab_srvice.get_project_commits(project["id"],0 ,50 )
          commits.each do |commit|
            committers.push(commit["committer_name"])
          end
          project["committers"] =  committers.uniq
        end
        r = @api_service.upload_app(list)
        pp r
      end

      def update_component_data
        data = @gitlab_srvice.get_all_components

        list = data.parsed_response['projects']



        list.each do |project |
          committers = [];
          commits = @gitlab_srvice.get_project_commits(project["id"],0 ,50 )


          commits.each do |commit|
            committers.push(commit["committer_name"])
          end
          project["committers"] =  committers.uniq
        end

        r = @api_service.upload_component(list)
        pp r
      end

      def update_third_lib_data
        data = @gitlab_srvice.get_third_party_lib_projects
        list = data.parsed_response['projects']
        r = @api_service.upload_third_lib_project(list)
        pp r
      end

      def create_new_component(name, desc)
        r = @gitlab_srvice.create_project(name, desc)
        if r.response.code == "201"
          pp "创建成功"
          url = r.parsed_response["http_url_to_repo"]
          pp "repo url :#{url}"
        else
          pp "创建失败"
          pp r.parsed_response['message']
        end

      end

      def find_project(name)
        r = @gitlab_srvice.search_project(name)
      end

      def delete_component(name)

        res = find_project(name)
        id = 0
        res.each do |project_hash|
          if project_hash["namespace"]["id"] == 514 && project_hash["name"] == name
            id = project_hash['id']
          end
        end

        if id == 0
          pp '未找到相关的工程'
        end
        r = @gitlab_srvice.delete_project(id) unless id == 0

        if r != nil
          if r.code == 200
            pp "#{name} 成功删除"
          else
            pp "#{name} 删除失败,"
          end
        end
      end

    end

  end

end