# Copyright 1999-2016. Parallels IP Holdings GmbH. All Rights Reserved.
package SiteApp;

use strict;
eval{require warnings;1;};

use PleskVersion;
use SiteApp::SiteApp;
use SiteApp::SiteApp10;
use SiteApp::SiteAppGlobalSettings;

sub getServerSettingsForApplications {  
  if ( PleskVersion::atLeast( 10, 3, 0 ) ) {
    return map { SiteApp::SiteAppGlobalSettings->new($_) } SiteApp::SiteAppGlobalSettings::getSappsGlobalSettings() ;
  }
}

sub getDomainSiteapps {
  my ($dom_id, $dbh) = @_;
  # Site applications migration is supported since Plesk 7.0.0
  if ( PleskVersion::atLeast( 10, 0, 0 ) ) {
    return _getDomainSiteapps10($dom_id);
  }
  else {
    return _getDomainSiteapps($dom_id, $dbh);
  }
  return;
}

sub _getDomainSiteapps10 {
  my ($webspaceId) = @_;
  return map { SiteApp::SiteApp10->new($_) } SiteApp::SiteApp10::getSappMetas($webspaceId, undef) ;
}

sub _getDomainSiteapps {
  my ( $dom_id, $dbh ) = @_;

  my @SiteApplications;
  my @sapp_ids;

  # ids of site apps installed on domain
  my $sql = "SELECT id FROM SiteApps WHERE dom_type='domain' AND dom_id=?";
  if ( $dbh->execute_rownum($sql, $dom_id) ) {
    while ( my $idRow = $dbh->fetchrow() ) {
      push @sapp_ids, $idRow->[0];
    }
  }
  $dbh->finish();

  # subdomains
  $sql = "SELECT id FROM subdomains WHERE dom_id=?";
  my (@subdoms);
  if ( $dbh->execute_rownum($sql, $dom_id) ) {
    while ( my $subdomRow = $dbh->fetchrow() ) {
      push @subdoms, $subdomRow->[0];
    }
  }
  $dbh->finish();

  # ids of site apps installed on subdomains
  foreach my $subdom_id (@subdoms) {
    $sql = "SELECT id FROM SiteApps WHERE dom_type='subdomain' AND dom_id=?";
    if ( $dbh->execute_rownum($sql, $subdom_id) ) {
      while ( my $idRow = $dbh->fetchrow() ) {
        push @sapp_ids, $idRow->[0];
      }
    }
    $dbh->finish();
  }

  foreach my $sapp_id (@sapp_ids) {
    my $sapp = SiteApp::SiteApp->new( $sapp_id, $dbh );
    if ( $sapp->error() ) {
      my $sapp_prefix = $sapp->getInstallPrefix(); 
      my $details = $sapp->error();
      Logging::warning("Cannot dump site app with id '$sapp_id'" . (defined $sapp_prefix ? " and prefix '$sapp_prefix'"  : "") . ". "
                     . "However, all the app-related content should be transferred correctly. [$details]", 'SiteappError');
      next;
    }
    push @SiteApplications, $sapp;
  }

  return @SiteApplications;
}



1;
