 defmodule Resume.ResumeController do
   use Resume.Web, :controller
 
-  import Resume.Controllers.Helpers
+  alias Resume.Controllers.Helpers, as: Helper
+  alias Resume.Skill
+  alias Resume.Experience
+  alias Resume.Education
+  alias Resume.Reference
+  alias Resume.Award
 
   alias Resume.Resume
+  alias Ecto.Changeset, as: Changeset
 
   def index(conn, _params) do
     resumes = Repo.all(Resume)

    |> put_flash(:info, "Resume deleted successfully.")
    |> redirect(to: resume_path(conn, :index))
  end
end


  def show(conn, %{"id" => id}) do
    resume = Repo.get!(Resume, id)
    |> Helper.preload_attributes

    render(conn, "show.html", resume: resume)
  end

  def edit(conn, %{"id" => id}) do
    resume = Repo.get!(Resume, id)
    changeset = Resume.changeset(resume)

    user = Coherence.current_user(conn) |> Helper.preload_attributes
    render(conn, "edit.html", resume: resume, changeset: changeset,
                             user: user,
                             skill_ids: [],
                             exp_ids: [],
                             edu_ids: [],
                             award_ids: [],
                             ref_ids: [])
  end

  def update(conn, %{"id" => id, "resume" => resume_params}) do
    resume = Repo.get!(Resume, id)
    changeset = Resume.changeset(resume, resume_params)

    checked_skills_ids = checked_ids(conn, "checked_skills")
    checked_educations_ids = checked_ids(conn, "checked_educations")
    checked_experiences_ids = checked_ids(conn, "checked_experiences")
    checked_references_ids = checked_ids(conn, "checked_references")
    checked_awards_ids = checked_ids(conn, "checked_awards")

    case Repo.update(changeset) do
      {:ok, resume} ->
        do_update_intermediate_table(Skill, :skills, resume.id, checked_skills_ids)
        do_update_intermediate_table(Education, :educations, resume.id, checked_educations_ids)
        do_update_intermediate_table(Experience, :experiences, resume.id, checked_experiences_ids)
        do_update_intermediate_table(Reference, :references, resume.id, checked_references_ids)
        do_update_intermediate_table(Award, :awards, resume.id, checked_awards_ids)

        conn
        |> put_flash(:info, "Resume updated successfully.")
        |> redirect(to: resume_path(conn, :show, resume))
