/**
 *
 * Copyright (c) Microsoft Corporation. All rights reserved.
 * Licensed under the MIT License. See License.txt in the project root for license information.
 *
 */

package com.microsoft.azure.management.appservice.samples;

import com.microsoft.azure.management.Azure;
import com.microsoft.azure.management.appservice.AppServicePricingTier;
import com.microsoft.azure.management.appservice.PhpVersion;
import com.microsoft.azure.management.appservice.WebApp;
import com.microsoft.azure.management.resources.fluentcore.arm.Region;
import com.microsoft.azure.management.resources.fluentcore.utils.ResourceNamer;
import com.microsoft.azure.management.samples.Utils;
import com.microsoft.azure.management.sql.SqlDatabase;
import com.microsoft.azure.management.sql.SqlServer;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Azure App Service basic sample for managing web apps.
 *  - Create a storage account and upload a couple blobs
 *  - Create a web app that contains the connection string to the storage account
 *  - Deploy a Tomcat application that reads from the storage account
 *  - Clean up
 */
public final class ManageWebAppSqlConnection {

    private static OkHttpClient httpClient;

    /**
     * Main entry point.
     * @param args the parameters
     */
    public static void main(String[] args) {
        // New resources
        final String suffix         = ".azurewebsites.net";
        final String appName        = ResourceNamer.randomResourceName("webapp1-", 20);
        final String appUrl         = appName + suffix;
        final String sqlServerName  = ResourceNamer.randomResourceName("jsdkserver", 20);
        final String sqlDbName      = ResourceNamer.randomResourceName("jsdkdb", 20);
        final String admin          = "jsdkadmin";
        final String password       = "StrongPass!123";
        final String planName       = ResourceNamer.randomResourceName("jplan_", 15);
        final String rgName         = ResourceNamer.randomResourceName("rg1NEMV_", 24);

        try {

            //=============================================================
            // Authenticate

            final File credFile = new File(System.getenv("AZURE_AUTH_LOCATION"));

            Azure azure = Azure
                    .configure()
                    .withLogLevel(HttpLoggingInterceptor.Level.BASIC)
                    .authenticate(credFile)
                    .withDefaultSubscription();

            // Print selected subscription
            System.out.println("Selected subscription: " + azure.subscriptionId());
            try {


                //============================================================
                // Create a sql server

                System.out.println("Creating SQL server " + sqlServerName + "...");

                SqlServer server = azure.sqlServers().define(sqlServerName)
                        .withRegion(Region.US_WEST)
                        .withNewResourceGroup(rgName)
                        .withAdministratorLogin(admin)
                        .withAdministratorPassword(password)
                        .create();

                System.out.println("Created SQL server " + server.name());

                //============================================================
                // Create a sql database for the web app to use

                System.out.println("Creating SQL database " + sqlDbName + "...");

                SqlDatabase db = server.databases().define(sqlDbName)
                        .withoutElasticPool()
                        .withoutSourceDatabaseId()
                        .create();

                System.out.println("Created SQL database " + db.name());

                //============================================================
                // Create a web app with a new app service plan

                System.out.println("Creating web app " + appName + "...");

                WebApp app = azure.webApps()
                        .define(appName)
                        .withExistingResourceGroup(rgName)
                        .withNewAppServicePlan(planName)
                        .withRegion(Region.US_WEST)
                        .withPricingTier(AppServicePricingTier.STANDARD_S1)
                        .withPhpVersion(PhpVersion.PHP5_6)
                        .defineSourceControl()
                            .withPublicGitRepository("https://github.com/ProjectNami/projectnami")
                            .withBranch("master")
                            .attach()
                        .withAppSetting("ProjectNami.DBHost", server.fullyQualifiedDomainName())
                        .withAppSetting("ProjectNami.DBName", db.name())
                        .withAppSetting("ProjectNami.DBUser", admin)
                        .withAppSetting("ProjectNami.DBPass", password)
                        .create();

                System.out.println("Created web app " + app.name());
                Utils.print(app);

                //============================================================
                // Allow web app to access the SQL server

                System.out.println("Allowing web app " + appName + " to access SQL server...");

                SqlServer.Update update = server.update();
                for (String ip : app.outboundIpAddresses()) {
                            update = update.withNewFirewallRule(ip);
                }
                server = update.apply();

                System.out.println("Firewall rules added for web app " + appName);
                Utils.print(server);

                System.out.println("Your WordPress app is ready.");
                System.out.println("Please navigate to http://" + appUrl + " to finish the GUI setup. Press enter to exit.");
                System.in.read();

            } catch (Exception e) {
                System.err.println(e.getMessage());
                e.printStackTrace();
            } finally {
                try {
                    System.out.println("Deleting Resource Group: " + rgName);
                    azure.resourceGroups().beginDeleteByName(rgName);
                    System.out.println("Deleted Resource Group: " + rgName);
                } catch (NullPointerException npe) {
                    System.out.println("Did not create any resources in Azure. No clean up is necessary");
                } catch (Exception g) {
                    g.printStackTrace();
                }
            }

        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
    }

    private static String curl(String url) {
        Request request = new Request.Builder().url(url).get().build();
        try {
            return httpClient.newCall(request).execute().body().string();
        } catch (IOException e) {
            return null;
        }
    }

    static {
        httpClient = new OkHttpClient.Builder().readTimeout(1, TimeUnit.MINUTES).build();
    }
}

@@ -1041,201 +1041,269 @@
 e a 
-storage account and upload a couple blobs%0A *  - Create a web app that contains the connection str
+SQL database in a new SQL server%0A *  - Create a web app deployed with Project Nami (WordPress's SQL Server variant)%0A *      that contains the app sett
 ing
+s
  to 
-the storage account%0A *  - Deploy a Tomcat application that reads from the storage account
+connect to the SQL database%0A *  - Update the SQL server's firewall rules to allow the web app to access
 %0A * 

Update comments for new sample