 #_
 (comment
   (defonce cli
-   (get-or-make-client "Org1Msp"
+   (get-or-make-client "Org1MSP"
                 "PeerAdmin"
                 (-> (slurp "resources/creds/cd96d5260ad4757551ed4a5a991e62130f8008a0bf996e4e4b84cd097a747fec-priv")
                     (keys/str->private-key))

                                      (.getCert ^Enrollment enrollment))]
    (swap! client-lru-cache cache/evict cache-key)))

(defrecord ClientOpts [roles account affiliation])

(defn get-or-make-channel [client channel-id]
  (or (client/get-channel client channel-id) (client/new-channel client channel-id)))

(defprotocol ChannelEndOpts
  (new-channel-end [channel-end client])
  (get-channel-ends [channel-end client]))

;; Channel ends are: Peers(Endorsers,...), Orderers
(defrecord OrdererOpts [name grpc-url properties]
  ChannelEndOpts
    (new-channel-end [{:keys [name grpc-url properties]} client]
    (client/new-orderer client name grpc-url properties))
  (get-channel-ends [this channel]
    (channel/get-orderers channel)))

(defrecord PeerOpts [name grpc-url properties]
  ChannelEndOpts
  (new-channel-end [{:keys [name grpc-url properties]} client]
    (client/new-orderer client name grpc-url properties))
  (get-channel-ends [this channel]
    (channel/get-peers channel)))

(defprotocol ChannelEnd
  (add-channel-end-to-channel [channel-end channel]))
  
(extend-protocol ChannelEnd
  Orderer
  (add-channel-end-to-channel [this channel]
    (channel/add-orderer channel this)))

(extend-protocol ChannelEnd
  Peer
  (add-channel-end-to-channel [this channel]
    (channel/add-peer channel this)))

;;;
;;; High level interface
;;;
(defn get-or-make-client [msp-id name priv-key cert opts]
  (let [cache-key (priv-key+cert->hash priv-key cert)
        lru-cache (swap! client-lru-cache cache/hit cache-key)]
    (if-let [existing-client (cache/lookup lru-cache cache-key)]
      existing-client
      (let [new-client (make-client msp-id name priv-key cert opts)]
        (swap! client-lru-cache cache/miss cache-key new-client)
        new-client))))

(defn add-channel-end
  ([client channel-id channel-end-opts]

                            (chaincode/set-path "resources/")
                            (chaincode/build)))
  (request/set-chaincode-id req chaincode-id)
  (request/set-fcn req "createCar")
  ;; timeout
  (request/set-proposal-wait-time req 10000)
  ;; FIXME: marshall
  (request/set-args req (java.util.ArrayList. ["CAR10" "Chevy" "Volt" "Red" "Nick"]))

  (defonce resp (channel/send-transaction-proposal chan req))
  (defonce future1 (channel/send-transaction chan resp (client/get-user-context cli)))
