require 'csv'
require 'json'

class DataWriter
  def initialize(file_name)
    @file_name = file_name
  end

  def read_data
    if File.exist?(file_path)
      return CSV.read(file_path)
    else
      return nil
    end
  end

  def build_exists?(number)
    data = read_data

    return nil if data.nil?

    data.each do |x|
      build_num = x[0]
      date = x[1]
      time = x[2]
      build_name = x[3]
      result = x[4]
      dev = x[5]
      env = x[6]
      smoca_triggered = x[7]

      if build_num.to_s == number.to_s
        return {'buildNumber' => build_num, 'buildName' => build_name, 'buildResult' => result,
            'initiatedBy' => dev, 'date' => date, 'time' => time, 'environment' => env, 'smoca_triggered' => smoca_triggered}
      end
    end

    return nil
  end

  def save_data(data)

    build_num = data['buildNumber']
    build_name = data['buildName']
    build_result = data['buildResult']
    initiated_by = data['initiatedBy']
    date = data['date']
    time = data['time']
    env = data['environment']
    smoca_triggered = data['smoca_triggered']

    CSV.open(file_path, 'a+') do |csv|
      csv << [build_num, date, time, build_name, build_result, initiated_by, env, smoca_triggered]
    end
  end

  def file_path
    return "./csv/#{@file_name}"
  end
end
