# frozen_string_literal: true

require "thor"

require_relative "../base"

module Neetob
  class CLI
    module Github
      module Issues
        class Create < Base
          attr_accessor :repos, :issue_title, :issue_description, :issue_assignee, :issue_labels, :sandbox

          def initialize(repos, issue_title, issue_description = "", issue_assignee = "", issue_labels = "",
sandbox = false)
            super()
            @repos = repos
            @issue_title = issue_title
            @issue_description = issue_description
            @issue_assignee = issue_assignee
            @issue_labels = issue_labels
            @sandbox = sandbox
            get_issue_title_or_description_and_confirm_data
          end

          def run
            matching_repos = find_all_matching_apps_or_repos(repos, :github, sandbox)
            matching_repos.each do |repo|
              ui.info("\nCreating issue in \"#{repo}\"  \n")
              begin
                issue_options = { assignee: issue_assignee, labels: issue_labels }
                issue = client.create_issue(repo, issue_title, issue_description, issue_options)
                ui.success("Created the issue successfully \nLink: #{issue[:html_url]}")
              rescue StandardError => e
                ExceptionHandler.new(e).process
              end
            end
          end

          private

            def get_issue_title_or_description_and_confirm_data
              until issue_title.present?
                ui.info("Enter the issue title below. Once you are done then just press enter:\n~ ")
                @issue_title = STDIN.gets.chomp
                ui.say("Title can't be blank.") if issue_title.blank?
              end
              if issue_description.blank?
                ui.info(
                  "Enter the issue body below. Once you are done then press Ctrl-D: " +
                  "(While creating the issue body you can use the enter key to type multiline message)\n")
                @issue_description = STDIN.read.chomp
              end
              ui.info(
                "Please review the issue title & the issue body that you have typed and also check the repos " +
                "for which issues will be created. If everything looks good then type " +
                "\"proceed\" below. Type anything else to cancel the operation.\n~ ")
              proceed = STDIN.gets.chomp
              ui.error("Cancelled creating issue(s)") and exit(true) if proceed.casecmp?("proceed") == false
            end
        end
      end
    end
  end
end