import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.*;
import java.lang.Throwable;

public class Main
{
  public static Model model;

  public static void main(String[] args)
  {
    JFrame window = new JFrame("Fotag!");
    model = new Model();
    
    try
    {
      FileInputStream file = new FileInputStream("savestate.shit");
      ObjectInputStream object =  new ObjectInputStream(file);
      model = (Model)object.readObject();
      object.close();
    }
    catch (Exception e) {System.out.println("Playing baseball");}
    
    Gallery gallery = new Gallery(model);
    Controls controls = new Controls(model);
    model.notifyObservers();
    
    // create a layout panel to hold the views
    JPanel mainpanel = new JPanel(new BorderLayout(0, 0));
    window.getContentPane().add(mainpanel);
    JScrollPane scrollGallery = new JScrollPane(gallery);
    scrollGallery.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
    scrollGallery.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    mainpanel.add(scrollGallery, BorderLayout.CENTER);
    mainpanel.add(controls, BorderLayout.PAGE_START);

    // Setup the frame to do frame things
    window.setPreferredSize(new Dimension(1280,720));
    window.setMinimumSize(new Dimension(320, 180));
    window.pack();
    //window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    
    window.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
    window.addWindowListener(new WindowAdapter()
    {
      public void windowClosing(WindowEvent we)
      {
          String ObjButtons[] = {"Yes","No"};
          int PromptResult = JOptionPane.showOptionDialog(null,"Do you want to save your files?","",JOptionPane.DEFAULT_OPTION,JOptionPane.WARNING_MESSAGE,null,ObjButtons,ObjButtons[1]);
          
          if(PromptResult==JOptionPane.YES_OPTION)
          {
            try
            {
              ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("savestate.shit"));
              output.writeObject(model);
              output.close();
            } catch (Exception e)
            {
              System.out.println("Screw you ankil");
              e.printStackTrace();
            }
          }
          
          System.exit(0);
      }
    });
    
    window.setVisible(true);
  }
}
