require 'open-uri'
require 'openssl'
require_relative 'scripts/utils'
require_relative 'scripts/wix'
require_relative 'scripts/copy-dependencies'

OpenSSL::SSL::VERIFY_PEER = OpenSSL::SSL::VERIFY_NONE

MANUFACTURER = 'Open Systems Pharmacology'
PRODUCT_NAME = "#{MANUFACTURER} Suite"
GITHUB_NAME = 'open-systems-pharmacology'
APPVEYOR_ACCOUNT_NAME = 'open-systems-pharmacology-ci'

VARIABLES = {}
MSI = {}

desc "Create suite setup"
task :create_setup,[:product_version, :branch_name]  do |t, args|
  @product_version = args.product_version
  @branch_name = args.branch_name || 'develop'
  release_version_split = @product_version.split('.')
  @product_release_version = "#{release_version_split[0]}.#{release_version_split[1]}"
  @product_full_version = "#{@product_release_version}.#{release_version_split[2]}"
  @product_full_name = "#{PRODUCT_NAME} #{@product_full_version}"

  VARIABLES[:ProductName] =  PRODUCT_NAME
  VARIABLES[:Manufacturer] =  MANUFACTURER
  VARIABLES[:ProductFullName] =  @product_full_name
  VARIABLES[:ProductVersion] =  @product_version
  VARIABLES[:ProductFullVersion] =  @product_full_version

  MSI[:pksim] = create_package('pk-sim', 'PK-Sim')
  MSI[:mobi] = create_package('mobi', 'MoBi')
  MSI[:validator] = create_package('installationvalidator', 'InstallationValidator')
  
  Rake::Task['prepare_all_packages'].invoke
  
  create_versions_file
  create_setup compressed:'no', output_name:'OSPSuite-WebInstall' 
  create_setup compressed:'yes', output_name:'OSPSuite-Full'  
end

def create_versions_file
  version_file = File.join(output_dir,'versions.txt')
  File.open(version_file, 'w') do |file| 
    MSI.each do |key, package|
      file.puts "#{package[:git_repository]}: #{package[:file_name]}"
    end
  end
end

def create_package(project_name,  git_repository, version: @product_version, branch: @branch_name, uri:nil)
  git_repo = git_repository || project_name

  return {
    project_name: project_name,
    branch: branch,
    compressed: true,
    git_repository: git_repo,
    version: version,
    uri:uri
  } 
end

def run_candle(compressed)
  all_variables = VARIABLES.each.collect do |k, v|
    "-d#{k}=#{v}"
  end
  command_line = %W[#{deploy_dir}/bundle.wxs -dCompressed=#{compressed} -ext WixUtilExtension -ext WixNetFxExtension -ext WixBalExtension -o #{deploy_dir}/]
  Utils.run_cmd(Wix.candle, command_line + all_variables)
end

desc "Runs the light command that actually creates the msi package"
def run_light(exe)
  command_line = %W[#{deploy_dir}/Bundle.wixobj -o #{exe} -nologo -ext WixUIExtension -ext WixNetFxExtension -ext WixBalExtension -spdb -b #{deploy_dir}/ -cultures:en-us]
  Utils.run_cmd(Wix.light, command_line)
end

def create_setup(compressed:'yes', output_name:'OSPSuite')
  exe = File.join(output_dir,"#{output_name}.#{@product_full_version}.exe")
  run_candle compressed
  run_light exe
  puts exe
end

desc "Prepare downloaded installers"
task :prepare_all_packages => :clean do
  MSI.keys.each do |msi|
      prepare_msi(msi)
  end
end

desc "cleanup files before starting compilation"
task :clean do
  FileUtils.mkdir_p deploy_dir  
  FileUtils.mkdir_p output_dir  

  copy_depdencies current_dir,  deploy_dir do
    copy_files 'setup', '*'
  end
end

def prepare_msi(msi)
  package =  MSI[msi]

  package[:file_name] = retrieve_package_name(package) 
  VARIABLES[msi] = package[:file_name]
end

def retrieve_package_name(package)
  msi_dir = File.join(deploy_dir, package[:project_name])
  copy_msi_to_deploy msi_dir  
end

#copy all msi packages defined under dir and return the name of the packages found (should only be one)
def copy_msi_to_deploy(dir)
  artifact_name = ''
  Dir.glob(File.join(dir, '*.msi')) do |x|
    copy x, deploy_dir
    artifact_name = File.basename(x)
  end 
  artifact_name
end

def deploy_dir
  File.join(current_dir,'deploy')
end

def output_dir
  File.join(current_dir,'output')
end

def current_dir
  File.dirname(__FILE__)
end