 defmodule Yodado.Web.Admin.FeatureStatusHandler do
+
+  defrecord State, c: nil, feature: nil
+
   def init(_transport, _req, _opts) do
     {:upgrade, :protocol, :cowboy_rest}
   end
 
   def rest_init(req, _opts) do
-    {:ok, req, []}
+    state = State.new(c: Yodado.FeaturePersistence.new)
+    {:ok, req, state}
   end
 
   def allowed_methods(req, state) do

  end

  def service_available(req, state) do
    persistence_ok = Yodado.FeaturePersistence.ping
    {persistence_ok, req, state}
  end

  def resource_exists(req, state) do
    {feature_id, req} = :cowboy_req.binding(:feature_id, req)
    case Yodado.FeaturePersistence.find_feature(feature_id) do
      :not_found ->     {false, req, state}
      {:ok, feature} -> state = Keyword.put(state, :feature, feature)
                        {true, req, state}
    end
  end

  def save_feature(req, state) do
    {:ok, feature_json, req} = :cowboy_req.body(req)
    feature = feature_json |> JSEX.decode!(labels: :atom) |> Yodado.Feature.from_json
    Yodado.FeaturePersistence.save_feature(feature, state.c)
    {true, req, state}
  end

  def delete_resource(req, state) do
    {feature_id, req} = :cowboy_req.binding(:feature_id, req)
    Yodado.FeaturePersistence.delete_feature(feature_id, state.c)
    {true, req, state}
  end
end
