require 'openssl'
require 'base64'
require 'json'

class MyAesCrypt
	@cipher = ""

	def initialize
		@cipher = OpenSSL::Cipher::Cipher.new(ENV["CIPHER_TYPE"])		
	end

	def export_key(passphrase)
		# We want a 256 bit key symetric key based on passphrase
		# for cloud is lookup
		# for local is license_key
		# iv_salt = passphrase+"c2l"
		passphrase = passphrase + ENV['SX_KEY']
		passphrase = passphrase.gsub(".","_")
		digest = Digest::SHA256.new
		key_digest = digest.update(passphrase)			
		key = key_digest.digest
		
		# iv = iv_digest.digest
		ENV['AES_KEY']  = cipher_key = Base64.encode64(key) # stores the key in key, and also sets the generated key on the @cipher
		ENV['AES_IV']  = cipher_iv = Base64.encode64(@cipher.random_iv) # stores the iv in iv, and also sets the generated iv on the @cipher
		return cipher_key, cipher_iv
	end

	def export_to_file(passphrase)
		file_path = "config/shops.json"
		aes_key, aes_iv = export_key(passphrase)
		tmpHash = { 			
			"lookup" => passphrase,
			"value" => 
			{
				"key"	 => aes_key,
				"iv"	 => aes_iv
			}
		}

		shop_data = File.read(file_path)

		shop_json = JSON.parse(shop_data)	
		shop_json["data"].each do |j|
			if j["lookup"] == passphrase				
				return j["value"]["key"], j["value"]["iv"]
			end
		end

		shop_json["data"] << tmpHash

		File.open(file_path, "w") { |io|
			io.puts JSON.pretty_generate(shop_json)
		}

		return aes_key, aes_iv
	end

	private
	def encrypt(data)
		cipher.encrypt
		cipher.key = ENV["aes_key"]
		cipher.iv = ENV["aes_iv"]
		encrypted = cipher.update(data) + cipher.final
		encrypted = Base64.encode64(encrypted)
		return encrypted
	end

	def decrypt(data) 
		cipher.decrypt
		cipher.key = ENV["aes_key"]
		cipher.iv = ENV["aes_iv"]

		# Start the decryption
		decoded = Base64.decode64(data)
		decrypted = cipher.update(decoded) + cipher.final
		return decrypted
	end
end