package com.tutego.exercise.thread;

import java.io.IOException;
import java.net.*;
import java.time.*;
import java.util.concurrent.*;

//tag::solution-1[]
record WebResourceLastModifiedCallable(URL url) implements Callable<ZonedDateTime> {
  @Override public ZonedDateTime call() throws IOException {
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    long dateTime = con.getLastModified();
    con.disconnect();
    return ZonedDateTime.ofInstant( Instant.ofEpochMilli( dateTime ),
                                    ZoneId.of( "UTC" ) );
  }
}
//end::solution-1[]

public class PageLastModifiedCallableDemo {
  public static void main( String[] args ) throws MalformedURLException {
    //tag::solution-2[]
try ( var executorService = Executors.newCachedThreadPool() ) {
  URL url = URI.create( "https://en.wikipedia.org/wiki/Main_Page" ).toURL();
  Callable<ZonedDateTime> callable = new WebResourceLastModifiedCallable( url );
  Future<ZonedDateTime> dateTimeFuture = executorService.submit( callable );

  try {
    System.out.println(
        executorService.submit( callable ).get( 1, TimeUnit.MICROSECONDS )
    );
  }
  catch ( InterruptedException | ExecutionException | TimeoutException e ) {
    e.printStackTrace();
  }

  try {
    ZonedDateTime wikiChangedDateTime = dateTimeFuture.get();
    System.out.println( wikiChangedDateTime );
    ZonedDateTime now = ZonedDateTime.now( ZoneId.of( "UTC" ) );
    System.out.println( Duration.between( wikiChangedDateTime, now ).toMinutes() );
  }
  catch ( InterruptedException | ExecutionException e ) {
    e.printStackTrace();
  }
}
    //end::solution-2[]
  }
}
