module Perkins
  class Application
    attr_accessor :host , :port, :working_dir, :redis, :database, :sse_endpoint
    attr_reader   :server
    attr_accessor :github_client_id, :github_client_secret

    class << self
      attr_accessor :instance
    end

    def initialize(opts={})
      @host = opts[:host] unless opts[:host].blank?
      @post = opts[:port] unless opts[:port].blank?
      @github_client_id = opts[:github_client_id] unless opts[:github_client_id].blank?
      @github_client_server = opts[:github_client_secret] unless opts[:github_client_secret].blank?
      working_dir = opts[:working_dir] unless opts[:working_dir].blank?
      self.class.instance = self
      self.init_github_client
      self
    end

    def database=(file)
      @dbconfig = YAML::load(File.open(file))
      @db = ActiveRecord::Base.establish_connection(@dbconfig[ENV['RACK_ENV']])
      setup_sidekiq
    end

    def database
      @db
    end

    def init_github_client
      #$github_client = Octokit::Client.new \
      #  :client_id     => @github_client_id,
      #  :client_secret => @github_client_server
      
      #GLOBAL SERVER 2 SERVER GITHUB CLIENT
      $github_client ||= Octokit::Client.new(
        login: ENV['LOGIN'],
        access_token: ENV['ACCESS_TOKEN']
      )
    
    end

    def redis=(opts={})
      namespace = opts.delete(:namespace) || :perkins
      redis_connection = Redis.new(opts)
      $redis = Redis::Namespace.new(namespace, :redis => redis_connection)
    end

    def as_json(options = {})
      data = {}
      fields = [:host, :port, :github_client_id,
                :github_client_secret, :working_dir]

      fields.each { |k| data[k] = send(k) }
      data
    end

    def setup_sidekiq
      # Sidekiq server is multi-threaded so our Redis connection pool size defaults to concurrency (-c)
      Sidekiq.configure_server do |config|
        config.redis = { :namespace => 'perkins-worker' }
        if defined?(ActiveRecord::Base)
          #ActiveRecord::Base.establish_connection
          #Perkins::Application.instance.database
          ActiveRecord::Base.establish_connection(@dbconfig[ENV['RACK_ENV']])
        end
      end

      Sidekiq.configure_client do |config|
        config.redis = { :namespace => 'perkins-worker' }
      end

    end

  end
end