require_relative 'stack_template_base'
require 'securerandom'

module Devops
  module Model
    class StackTemplateAws < StackTemplateBase

      # In Amazon Cloudformation the template file must be stored on an Amazon S3 bucket.
      field :template_url, type: String

      def update_template_url
        uniq_filename = "#{id}-#{SecureRandom.hex}.template"
        s3_file = provider_instance.store_stack_template(uniq_filename, template_body)
        self.template_url = s3_file['url']
      end

      def parse_parameters
        template_hash = JSON.parse(template_body)
        return {} unless template_hash['Parameters']

        parameters = {}
        template_hash['Parameters'].each do |param_name, param_info|
          # use String always for now
          parameters[param_name] = {'type' => 'String', 'description' => param_info['Description']}
        end
        parameters
      rescue
        {}
      end

      class << self
        def create(attrs)
          model = super(attrs)
          model.update_template_url
          model
        end
      end

    end
  end
end
