;;; -*- mode: clojure -*-

;;; Disable logging
(System/setProperty "org.apache.commons.logging.Log"
                    "org.apache.commons.logging.impl.NoOpLog")

(ns org.salvipeter.HajraViki
  (:import (java.awt BorderLayout Font)
           (javax.swing JFrame JLabel)
           (org.apache.commons.httpclient HttpClient NameValuePair)
           (org.apache.commons.httpclient.methods PostMethod))
  (:gen-class))

;;; Parameters
(def *support-uri* "http://bridge.chinese.cn/ajax/supportUser.jsp")
(def *viki-id* 16818)

;;; Main code
(defn post [uri parameter-map]
  (let [method (PostMethod. uri)
        parameters (for [[parameter value] parameter-map]
                     (NameValuePair. parameter value))]
    (.setRequestBody method (into-array parameters))
    (try (.executeMethod (HttpClient.) method)
         (.getResponseBodyAsString method)
         (finally (.releaseConnection method)))))

(defn good-response? [str]
  (.endsWith str "OK"))

;;; GUI
(defn support-user [id]
  (let [frame (JFrame.)
        hajra (JLabel. "  Hajrá Viki!  ")
        szavazat (JLabel. "Szavazatszámláló: 0")]
    (.setFont hajra (Font. "Serif" (bit-or Font/BOLD Font/ITALIC) 32))
    (doto frame
      (.setTitle "Hajra Viki")
      (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)
      (.setLayout (BorderLayout.))
      (.add hajra BorderLayout/PAGE_START)
      (.add szavazat BorderLayout/PAGE_END)
      (.pack)
      (.setLocationRelativeTo nil)
      (.setVisible true))
    (loop [i 0]
      (.setText szavazat (format "Szavazatszámláló: %d" i))
      (if (good-response? (post *support-uri* {"uid" (.toString id)}))
        (recur (inc i))
        (recur i)))))

(defn -main [& args]
  (support-user *viki-id*))