require 'time'
module Ads
  class AutoAd < Ads::Base
    attributes :channel_id, :ccp_start_date, :ccp_end_date, :density_target_minutes_per_hour, :surge_start_date, :surge_end_date, :surge_density_target_minutes_per_hour
    self.primary_attribute = :channel_id

    def self.invoke_get_channel_properties_table_entry(id)
      function_name = Settings.ads.vader_lambda_arn
      session_name = "10342598-9e52-4fbd-9cb8-2d4a10941b8c"
      aws_credentials = Aws::AssumeRoleCredentials.new(
        client: Aws::STS::Client.new(region: 'us-west-2'),
        role_arn: Settings.ads.vader_role_arn,
        role_session_name: session_name
      )

      client = Aws::Lambda::Client.new(region: 'us-west-2', credentials: aws_credentials)
      payload = {
        "httpMethod": "POST",
        "path": "/twirp/twitch.fulton.example.twitchvader.TwitchVader/GetChannelPropertiesTableEntry",
        "headers": {
            "Content-Type": "application/json"
        },
        "body": "{\"channel_id\":\"" + id + "\"}"
      }.to_json
      resp = client.invoke({
        function_name: function_name,
        invocation_type: 'RequestResponse',
        log_type: 'None',
        payload: payload
      })
      resp
    end

    def invoke_set_channel_properties_table_entry(channel_properties)
      function_name = Settings.ads.vader_lambda_arn
      session_name = "1f64a471-cd21-44ff-a55d-ac0a5fffd6fe"
      aws_credentials = Aws::AssumeRoleCredentials.new(
        client: Aws::STS::Client.new(region: 'us-west-2'),
        role_arn: Settings.ads.vader_role_arn,
        role_session_name: session_name
      )
      client = Aws::Lambda::Client.new(region: 'us-west-2', credentials: aws_credentials)
      payload = {
        "httpMethod": "POST",
        "path": "/twirp/twitch.fulton.example.twitchvader.TwitchVader/SetChannelPropertiesTableEntry",
        "headers": {
            "Content-Type": "application/json"
        },
        "body": "{\"properties\":" + channel_properties + "}"
      }.to_json
      resp = client.invoke({
        function_name: function_name,
        invocation_type: 'RequestResponse',
        log_type: 'None',
        payload: payload
      })
      resp
    end

    def self.find(id)
      resp = invoke_get_channel_properties_table_entry(id)
      body_json = JSON.parse(resp.payload.string)["body"]
      properties_json = JSON.parse(body_json)["properties"]
      ret_val = {}
      ret_val[:channel_id] = id
      if properties_json.key?("ccp_start_time") && properties_json.key?("ccp_end_time")
        ret_val[:ccp_start_date] = convert_unix_to_date(properties_json["ccp_start_time"])
        ret_val[:ccp_end_date] = convert_unix_to_date(properties_json["ccp_end_time"])
      end

      ret_val[:density_target_minutes_per_hour] = properties_json.key?("density_target_minutes_per_hour") ? properties_json["density_target_minutes_per_hour"] : 3

      if properties_json.key?("surge_start_time") && properties_json.key?("surge_end_time")
        ret_val[:surge_start_date] = convert_unix_to_date(properties_json["surge_start_time"])
        ret_val[:surge_end_date] = convert_unix_to_date(properties_json["surge_end_time"])
      end

      ret_val[:surge_density_target_minutes_per_hour] = properties_json.key?("surge_density_target_minutes_per_hour") ? properties_json["surge_density_target_minutes_per_hour"] : 3
      from_attributes(ret_val)
    end

    def save
      save_vals = {}
      save_vals["channel_id"] = self.attributes["channel_id"]
      if self.attributes["ccp_start_date"].present? && self.attributes["ccp_end_date"].present?
        save_vals["ccp_start_time"] = convert_date_to_unix(self.attributes["ccp_start_date"])
        save_vals["ccp_end_time"] = convert_date_to_unix(self.attributes["ccp_end_date"])
        save_vals["density_target_minutes_per_hour"] = self.attributes["density_target_minutes_per_hour"].to_i
      end
      if self.attributes["surge_start_date"].present? && !self.attributes["surge_end_date"].present?
        save_vals["surge_start_time"] = convert_date_to_unix(self.attributes["surge_start_date"])
        save_vals["surge_end_time"] = convert_date_to_unix(self.attributes["surge_end_date"])
        save_vals["surge_density_target_minutes_per_hour"] = self.attributes["surge_density_target_minutes_per_hour"].to_i
      end
      invoke_set_channel_properties_table_entry(save_vals.to_json)
    end

    def self.convert_unix_to_date(timestamp)
      Time.zone = 'UTC'
      tme = Time.strptime(timestamp, "%s")
      tme.strftime("%Y-%m-%dT%H:%M")
    end

    def convert_date_to_unix(date)
      if date == ""
        return
      end
      Time.zone = 'UTC'
      tme = Time.strptime(date, "%Y-%m-%dT%H:%M")
      tme.strftime("%s")
    end
  end
end
