class InitTemplatesController < ApplicationController
  before_action :authenticate_user!
  before_action :set_init_template, only: [:show, :destroy]

  def index
    @init_templates = InitTemplate.where(is_default: false, user_id: current_user.id)
  end

  def new
    @init_template = InitTemplate.new
  end

  def show
  end

  def create
    @init_template = InitTemplate.new(init_template_params)
    @init_template.details = get_ap_uplink_details(init_template_params[:ap_mac_id])
    respond_to do |format|
      if @init_template.save
        format.html { redirect_to init_templates_path, flash: { success:"Init Template was Successfully created."}}
      else
        format.html { redirect_to init_templates_path,flash: { error:"Oops! there was some problem in creating Init Template"}}
      end
    end
  end

  def edit
  end

  def update
  end

  def destroy
    if @init_template.destroy
      flash[:success] = "Successfully deleted InitTemplate"
    else
      flash[:error] = "Oops! there was some problem in deleting InitTemplate"
      Rails.logger.warn "#{@init_template.errors.full_messages}"
    end
    respond_to do |format|
      format.html { redirect_to init_templates_path }
      format.json { head :no_content }
    end
  end

  private

  def set_init_template
    @init_template = InitTemplate.where(:id => params[:id]).first
    if @init_template.blank?
      flash[:notice] = "Requested InitTemplate not found!"
      redirect_to init_templates_path
    end
  end

  def init_template_params
    params.require(:init_template).permit(:name,:template_type,:ap_mac_id).merge(user_id: current_user.id, organisation_id: current_user.organisation.id)
  end

  def get_ap_uplink_details(ap_mac_id)
    RouterInventory.where(mac_id: ap_mac_id).first.uplinks.map{|uplink| uplink.attributes.except("id","router_inventory_id","created_at","updated_at","last_mobile_status","last_seen_ip","nt","mm","cid","lac","lat","lng","imsi")}
  end
end
