require 'thor'
require 'fwtoolkit/cli/ext/thor'
require 'fwtoolkit/ext/gem'

module FWToolkit
  class Cocoapods < Thor
    include Thor::Actions

    desc 'setup', 'Install and configure cocoapods for the current user'
    option :'skip-install', :desc => 'Skip cocoapods gem install and only configure the fw repository'
    def setup
      install_cocoapods_gem unless options[:'skip-install']
      setup_cocoapods_repos
    end

    desc 'install [PROJECT_DIR]', 'Installs pods for the project at project_dir'
    def install(project_root)
      add_cocoapods_to_project project_root 
      if File.exist? File.join(project_root, 'Podfile')
        inside(project_root) {
            run! "bundle exec pod install", :capture => true
        }
      else
        say_status :skip, "Unable to locate the Podfile. Skipping pod install", :blue
      end
    end


    private

    def install_cocoapods_gem
      if inside(ENV['HOME']) {Gem::gem_available? 'cocoapods'}
        say_status :skip, 'Cocoapods is already installed', :blue
      else
         say_status :install, 'Installing cocoapods gem system-wise (requires root password)', :green
         run! 'sudo gem install cocoapods', {:capture => true}
      end
    end

    def setup_cocoapods_repos
      # I'm avoiding calling cocoapods directly in order not to need them as a dependecy for this set of commands
      say_status :warning, 'Cocoapods doesn\'t seem to be installed in your system. Please run fwt pods setup', :yellow if !Gem::gem_available?('cocoapods')
      fw_repo_path = File.join(ENV['CP_REPOS_DIR'] || "~/.cocoapods", 'fw')
      if Dir.exists? fw_repo_path
        say_status :skip, 'FW\'s podspec repository already installed', :blue
      else
        say_status :configure, 'Configuring FW\'s podspec repository', :green
        FileUtils.mkdir_p fw_repo_path
        inside(fw_repo_path) { run! 'git clone git@github.com:FutureWorkshops/FWTPodspecs.git .', :capture => true }
      end
    end

    def add_cocoapods_to_project(project_root)
      gemfile = File.join(project_root, 'Gemfile')
      raise Thor::Error, "Can't locate a valid Gemfile at path: #{File.expand_path project_root}" unless File.exist?(gemfile)

      unless cocoapods_in_gemfile? gemfile
        say_status :add, 'Add cocoapods to the Gemfile', :blue
        File.open(gemfile, "a") { |f| f.write 'gem "Cocoapods"' } 
        run! 'bundle', :capture => true
      end
    end

    def cocoapods_in_gemfile?(gemfile_path)
       File.read(gemfile_path).split("\n").select{ |line| line =~ /gem .Cocoapods./ }.count == 0
    end

    # def gemfile_gems_installed?(project_root)
    #   inside(project_root) do
    #     system('bundle check')
    #     $?.success?
    #   end
    # end
  end
end