# encoding: UTF-8
#
# Copyright (c) 2010-2017 GoodData Corporation. All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.

require_relative 'base_action'

module GoodData
  module LCM2
    class UpdateReleaseTable < BaseAction
      DESCRIPTION = 'Update Release Table'

      PARAMS = define_params(self) do
        description 'ADS Client'
        param :ads_client, instance_of(Type::AdsClientType), required: false

        description 'Client Used for Connecting to GD'
        param :gdc_gd_client, instance_of(Type::GdClientType), required: true

        description 'Organization Name'
        param :organization, instance_of(Type::StringType), required: false

        description 'Domain'
        param :domain, instance_of(Type::StringType), required: false

        description 'Segments to manage'
        param :segments, array_of(instance_of(Type::SegmentType)), required: true

        description 'Table Name'
        param :release_table_name, instance_of(Type::StringType), required: false

        description 'Query'
        param :query, instance_of(Type::GdSmartHashType), required: false
      end

      DEFAULT_TABLE_NAME = 'LCM_RELEASE'

      class << self
        def call(params)
          client = params.gdc_gd_client
          GoodData.gd_logger.info("Update release table: use_nfs=#{params.ads_client.nil?}")

          domain_name = params.organization || params.domain
          fail "Either organisation or domain has to be specified in params" unless domain_name
          client.domain(domain_name) || fail("Invalid domain name specified - #{domain_name}")

          params.segments.map do |segment_in|
            segment_id = segment_in.segment_id

            placeholders = {
              data_product_id: segment_in[:data_product_id],
              segment_id: segment_in[:segment_id],
              master_project_id: segment_in[:master_pid],
              version: segment_in[:version],
              timestamp: segment_in[:timestamp],
              table_name: params.release_table_name || DEFAULT_TABLE_NAME
            }

            update_release_table(params, placeholders, domain_name)

            {
              segment: segment_id,
              master_pid: segment_in[:master_pid],
              version: segment_in[:version],
              timestamp: segment_in[:timestamp]
            }
          end
        end

        def replace_placeholders(text, placeholders)
          result = text.dup
          placeholders.each do |k, v|
            result.gsub!("\#{#{k}}", v.to_s)
          end
          result
        end

        def update_release_table(params, placeholders, domain_id)
          if params.ads_client
            path = File.expand_path('../data/insert_into_lcm_release.sql.erb', __dir__)
            default_query = GoodData::Helpers::ErbHelper.template_file(path, placeholders)
            temp_query = (params.query && params.query.insert) || default_query
            query = replace_placeholders(temp_query, placeholders)

            params.ads_client.execute(query)
          else
            data_product_id = placeholders[:data_product_id]
            segment_id = placeholders[:segment_id]
            master_pid = placeholders[:master_project_id]
            version = placeholders[:version]
            GoodData::LCM2::Helpers.update_latest_master_to_nfs(domain_id, data_product_id, segment_id, master_pid, version)
          end
        end
      end
    end
  end
end
