 (ns gce.provider
   (:require
+   [clojure.core.strint :refer (<<)]
+   [clojure.data.json :refer (write-str)]
    [gce.validations :refer (validate-provider)]
-   [celestial.provider :refer (wait-for-ssh mappings wait-for)]
+   [celestial.provider :refer (wait-for-ssh mappings wait-for transform os->template)]
+   [clojure.java.data :refer (to-java from-java)]
    [celestial.core :refer (Vm)] 
    [taoensso.timbre :as timbre]
    [celestial.persistency.systems :as s]
    [celestial.model :refer (translate vconstruct)])
   (:import 
+    (com.google.api.services.compute.model Instance)
     (com.google.api.client.googleapis.javanet GoogleNetHttpTransport)
     (com.google.api.client.json.jackson2 JacksonFactory)
     (com.google.api.client.googleapis.auth.oauth2 GoogleCredential)


  (status [this]))

(defmethod translate :gce [{:keys [machine gce system-id] :as spec}]
    "Convert the general model into a gce instance"
    (mappings (merge machine gce {:system-id system-id}) []))

(defn validate [spec] 
  (validate-provider spec) spec)

(defmethod vconstruct :gce [spec]
  (Instance. (validate (translate spec))))

  (let [items (get (-> compute (.instances) (.list project zone) (.execute)) "items")]
    (map clojure.walk/keywordize-keys items)))

(defn create-instance [spec] 
  (.fromString (JacksonFactory/getDefaultInstance) (write-str spec) Instance))
 
(defmacro with-id [& body])

(defrecord GCEInstance [spec system]
  Vm
  (create [this] 
    (let [{:keys [id] :as instance} (create-instance spec) ]
     (debug "created" id)
     (s/partial-system (system :system-id) {:gce {:id id}})
      this))

  (start [this]
    (with-id
      (let [{:keys [machine]} (s/get-system (system :system-id))]
        (when-not (= "running" (.status this))
          )
        (wait-for-ssh (machine :ip) "root" [5 :minute]))
