/*
 * Copyright 2019 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.spanner;

import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;

/**
 * A quick-start sample that uses Spring Data Cloud Spanner to perform read, write, and DDL
 * operations.
 */
@org.springframework.boot.autoconfigure.SpringBootApplication
public class QuickStartSample implements CommandLineRunner {

  private static Logger LOG = LoggerFactory.getLogger(QuickStartSample.class);

  @Autowired SpannerSchemaToolsSample spannerSchemaToolsSample;

  @Autowired SpannerTemplateSample spannerTemplateSample;

  @Autowired SpannerRepositorySample spannerRepositorySample;

  public static void main(String[] args) {
    LOG.info("Starting Spring Data Cloud Spanner Sample.");
    SpringApplication.run(QuickStartSample.class, args);
    LOG.info("Spring Data Cloud Spanner Sample finished running.");
  }

  public void run(String... args) {
    /*
     This call creates both the Singer and Album tables with an interleaved relationship.
    */
    LOG.info("(SpannerSchemaToolsSample): Creating database tables if they don't exist.");
    spannerSchemaToolsSample.createTableIfNotExists();

    Singer singer = new Singer();
    singer.singerId = 1L;
    singer.firstName = "John";
    singer.lastName = "Doe";
    singer.albums =
        Arrays.asList(new Album(1L, 10L, "album1", 11L), new Album(1L, 20L, "album2", 12L));

    /*
     This call inserts the singer and performs a read query using a SpannerTemplate instance.
    */
    LOG.info("(SpannerTemplateSample): Saving one singer.");
    spannerTemplateSample.runTemplateExample(singer);

    /*
     This call uses queries defined in SingerRepository. The implementations of those queries
     are generated by Spring Data Cloud Spanner.
    */
    LOG.info("(SpannerRepositorySample): Running queries.");
    spannerRepositorySample.runRepositoryExample();

    /*
     This call drops both the sample Singer and Album tables.
    */
    LOG.info("(SpannerSchemaToolsSample): Dropping Singer and Album tables.");
    spannerSchemaToolsSample.dropTables();
  }
}
