// TODO: this "nice buttons" logic is pretty horrific
transient sclass JGallery extends MetaWithChangeListeners is Swingable {
  settableWithVar L<File> files;
  gettable File selectedFile;
  settable bool horizontal = true;
  
  event adaptingButton(JButton button, File file);

  simplyCached DynamicStack buttons() {
    ret horizontal ? makeNiceButtons() : verticalNiceButtons();
  }

  simplyCached ButtonImageLoader imageLoader() {
    ret new ButtonImageLoader(buttons());
  }
  
  void setImageFiles(Cl<File> filesCollection) swing {
    var files = asList(filesCollection);
    if (eq(this.files, files)) ret;
    setFiles(files);
    //printVars("JGallery.setImageFiles", n2(files));
    L<TextImageAction> l = filesForNiceButtons(files, lambda1 openImage);
    replaceNiceButtons(buttons(), l);
    
    for (btn, file : unpair zip(allButtons(buttons()), files))
      adaptingButton(btn, file);
      
    File selectedFile = selectedFile();
    selectFile(selectedFile);
    imageLoader().update();
  }
  
  void selectFile(File file) swing {
    selectedFile = file;
    int idx = indexOf(files, file);
    for (int i, JButton btn : unpair iterateWithIndex(allButtons(buttons()))) {
      bool selected = i == idx;
      setSelected(btn, selected);
      if (selected) {
        print("Selected button: " + btn);
        scrollIntoView(btn);
      }
    }
  }
  
  cachedVisual jHigherScrollPane(jfullcenter(buttons()));
  
  swappable void openImage(File f) { showImage(f); }
}