#     Copyright 2014 Netflix, Inc.
#
#     Licensed under the Apache License, Version 2.0 (the "License");
#     you may not use this file except in compliance with the License.
#     You may obtain a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#     Unless required by applicable law or agreed to in writing, software
#     distributed under the License is distributed on an "AS IS" BASIS,
#     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#     See the License for the specific language governing permissions and
#     limitations under the License.
require 'rest-client'
require 'base64'

class ScumblrTask::MoveVulnerabilityTask < ScumblrTask::Base
  include ActionView::Helpers::TextHelper
  def self.task_type_name
    "Move Vulnerability Task"
  end

  def self.task_category
    "Maintenance"
  end

  def self.config_options
    {}
  end

  def self.options
    return super.merge({:old_result_id =>{ name: "Old Result ID",
      description: "ID of the result you're moving the vulnerability from.",
      required: true
    },
    :new_result_id => { name: "New result ID",
       description: "ID of the result you're moving the vulnerability to.",
       required: true
     },
     :vulnerability_ids => { name: "Vulnerability IDs",
       description: "Comma separated list of IDs of the vulnerabilities to move",
       required: true
     }})
  end

  def initialize(options={})
    super
  end

  def run



    @old_result_id = @options["old_result_id"]
    @new_result_id = @options["new_result_id"]
    @vulnerability_ids = @options["vulnerability_ids"]

    @original_result = Result.find_by_id(@old_result_id)
    @new_result = Result.find_by_id(@new_result_id)

    if(!@original_result)
      create_error("Unable to find result with id #{@old_result_id}")
      return
    end
    if(!@new_result)
      create_error("Unable to find result with id #{@new_result_id}")
      return
    end

    @original_result.metadata ||={}
    @original_result.metadata["vulnerabilities"] ||=[]

    v_ids = @vulnerability_ids.split(",").map(&:strip)

    vulnerabilities = @original_result.metadata["vulnerabilities"].select{|v| v_ids.include?(v["id"])}

    if(vulnerabilities.length != v_ids.length)
      create_error("Unable to find vulnerabilities #{v_ids - vulnerabilities.map{|x| x["id"]}} in result #{@old_result_id}")
    end

    @new_result.metadata ||={}
    @new_result.metadata["vulnerabilities"] ||=[]
    @new_result.metadata["vulnerabilities"] |= vulnerabilities
    if(@new_result.save)
      @original_result.metadata["vulnerabilities"].delete_if{|v| v_ids.include?(v["id"])}
      @original_result.save
    else
      create_error("Unable to save result #{@new_result_id}")
    end

    return

  end

end
