             remote.write data
           remote.on 'data', (data) ->
             client.write data
+        # Write data directly to Shadowsocks
+        when 'shadowsocks'
+          remote = socks.createConnection
+            socksHost: config.get '127.0.0.1'
+            socksPort: config.get 'proxy.shadowsocks.local.port', 1080
+            host: remoteUrl.hostname
+            port: remoteUrl.port
+          remote.on 'connect', ->
+            client.write "HTTP/1.1 200 Connection Established\r\nConnection: close\r\n\r\n"
+            remote.write head
+          client.on 'data', (data) ->
+            remote.write data
+          remote.on 'data', (data) ->
+            client.write data
+        # Write data directly to HTTP proxy
         when 'http'
           host = config.get 'proxy.http.host', '127.0.0.1'
           port = config.get 'proxy.http.port', 8118
+          # Write header to http proxy
           msg = "CONNECT #{remoteUrl.hostname}:#{remoteUrl.port} HTTP/#{req.httpVersion}\r\n"
           for k, v of req.headers
             msg += "#{caseNormalizer(k)}: #{v}\r\n"


resolve = (req) ->
  switch config.get 'proxy.use'
    when 'socks5'
      return _.extend req,
        agentClass: SocksHttpAgent
        agentOptions:
          socksHost: config.get 'proxy.socks5.host', '127.0.0.1'
          socksPort: config.get 'proxy.socks5.port', 1080
    when 'http'
      host = config.get 'proxy.http.host', '127.0.0.1'
      port = config.get 'proxy.http.port', 8118
      return _.extend req,
        proxy: "http://#{host}:#{port}"
    else
      return req

class Proxy extends EventEmitter
  constructor: ->
    super()
    @load()
  load: ->
    self = @
    # HTTP Requests
    @server = http.createServer (req, res) ->
      delete req.headers['proxy-connection']
      req.headers['connection'] = 'close'
      parsed = url.parse req.url
      isGameApi = parsed.pathname.startsWith '/kcsapi'
      reqBody = new Buffer(0)
      req.on 'data', (data) ->
        reqBody = Buffer.concat [reqBody, data]
      req.on 'end', async ->

caseNormalizer = require 'header-case-normalizer'
request = Promise.promisifyAll require 'request'
requestAsync = Promise.promisify request
shadowsocks = require 'shadowsocks'
socks = require 'socks5-client'
SocksHttpAgent = require 'socks5-http-client/lib/Agent'

config = require './config'
{log, warn, error, resolveBody} = require './utils'

