require "./router"

class AdminRouter < Router
  def initialize
    get "/admin" do |env|
      layout "admin"
    end

    get "/admin/user" do |env|
      users = @context.storage.list_users
      username = get_username env
      layout "user"
    end

    get "/admin/user/edit" do |env|
      username = env.params.query["username"]?
      admin = env.params.query["admin"]?
      if admin
        admin = admin == "true"
      end
      error = env.params.query["error"]?
      current_user = get_username env
      new_user = username.nil? && admin.nil?
      layout "user-edit"
    end

    post "/admin/user/edit" do |env|
      # creating new user
      username = env.params.body["username"]
      password = env.params.body["password"]
      # if `admin` is unchecked, the body hash
      #   would not contain `admin`
      admin = !env.params.body["admin"]?.nil?

      @context.storage.new_user username, password, admin

      redirect env, "/admin/user"
    rescue e
      @context.error e
      redirect_url = URI.new \
        path: "/admin/user/edit",
        query: hash_to_query({"error" => e.message})
      redirect env, redirect_url.to_s
    end

    post "/admin/user/edit/:original_username" do |env|
      # editing existing user
      username = env.params.body["username"]
      password = env.params.body["password"]
      # if `admin` is unchecked, the body hash would not contain `admin`
      admin = !env.params.body["admin"]?.nil?
      original_username = env.params.url["original_username"]

      @context.storage.update_user \
        original_username, username, password, admin

      redirect env, "/admin/user"
    rescue e
      @context.error e
      redirect_url = URI.new \
        path: "/admin/user/edit",
        query: hash_to_query({"username" => original_username, \
                                 "admin" => admin, "error" => e.message})
      redirect env, redirect_url.to_s
    end

    get "/admin/downloads" do |env|
      mangadex_base_url = Config.current.mangadex["base_url"]
      layout "download-manager"
    end
  end
end
