package kz.cafe.admin.panel_extensions;

import java.io.*;
import kz.cafe.admin.constants.*;
import kz.cafe.admin.panels.*;
import kz.cafe.admin.panels.model.*;
import kz.cafe.constants.*;
import kz.cafe.db.*;
import kz.cafe.db.model.*;
import com.vaadin.ui.*;
import com.vaadin.ui.Upload.FailedEvent;
import com.vaadin.ui.Upload.FinishedEvent;
import com.vaadin.ui.Upload.StartedEvent;
import com.vaadin.ui.Upload.SucceededEvent;
import com.vaadin.ui.Window.Notification;
import com.vaadin.ui.themes.*;

public class ExtraPanelImageUploader extends AbstractExtendedPanel implements java.io.Serializable{
   private static final long serialVersionUID = 711754256190346567L;

   private final DBListPanel<?> pnlParent;
   private final Table table;
   private final CustomImageField cstField;
   
   private final Upload upload;
   
   private String sFileName;
   
   private Panel pnlImage = new Panel();
   
   
   public ExtraPanelImageUploader(final DBListPanel<?> pnlParent,
                                  final CustomImageField cstField){
      
      this.pnlParent = pnlParent;
      this.table = pnlParent.table;
      this.cstField = cstField;

      AbstractLayout panelLayout = (AbstractLayout) getContent();
      panelLayout.setMargin(false);      

      
      upload = new Upload(null, new Uploader());
      upload.setButtonCaption("Изображение");
      upload.setImmediate(true);

      
      upload.addListener(new Upload.StartedListener(){
         private static final long serialVersionUID = 5813862327410567135L;
         
         public void uploadStarted(StartedEvent event){
            // This method gets called immediatedly after upload is started
            upload.setEnabled(false);
         }
      });

      upload.addListener(new Upload.SucceededListener(){
         private static final long serialVersionUID = 103112353892881253L;

         public void uploadSucceeded(SucceededEvent event){
            
            File file = new File(ServerConstants.getImageFolder() + sFileName);
            if(file.length() > AdminConstants.IMAGE_MAX_SIZE){
               table.getApplication()
               .getMainWindow()
               .showNotification("ERROR",
                                 "Размер файла превышает " + AdminConstants.IMAGE_MAX_SIZE / 1024 + " килобайт",
                                  Notification.TYPE_WARNING_MESSAGE);
               return;
            }
            
            
//            table.getItem(table.getValue())
//                 .getItemProperty(ExtraPanelImage.this.field.name).setValue(
//                          image2ClickableLabel(sFileName, ExtraPanelImage.this.field.style.width)
//                            );
            
            
            MAbstractEditableDataElement recordToEdit = pnlParent.oldValueMongoObject;
            
            if(recordToEdit == null){
               recordToEdit = (MAbstractEditableDataElement) MongoService.get(pnlParent.classDB, (int) pnlParent.table.getValue());
            }
            
            
             
            try{
               java.lang.reflect.Field field = pnlParent.classDB.getField(cstField.db); 
               field.set(recordToEdit, sFileName);
            }
            catch (Throwable e){
               table.getApplication()
                        .getMainWindow()
                        .showNotification("ERROR",
                                          "Не могу добавить объект в базу " + e.toString(),
                                           Notification.TYPE_WARNING_MESSAGE);
            }            
            
            
            MongoService.save(recordToEdit);
            
            

//            
//            try{
//               Query q = MongoService.ds.createQuery(pnlParent.classDB).filter("ID", Long.parseLong("" + table.getValue()));
//               UpdateOperations uOps = MongoService.ds.createUpdateOperations(pnlParent.classDB).set(cstField.db, sFileName);
//               MongoService.ds.findAndModify(q, uOps);
//            }
//            catch (Throwable e){
//               table.getApplication().getMainWindow().showNotification(
//                        "ERROR",
//                        "Не могу добавить объект в базу " + e.toString(),
//                        Notification.TYPE_WARNING_MESSAGE);
//            }
            
            
            
            
            
            
            Object objReady;
            
            if(cstField.isImageInTable){
               objReady = image2ClickableLabel(sFileName, cstField.style.height);
            }
            else{
               objReady = sFileName;
            }
            table.getItem(table.getValue())
                     .getItemProperty(ExtraPanelImageUploader.this.cstField.name).setValue(objReady);
            
            ExtraPanelImageUploader.this.pnlParent.ahoyIveChangedSomething();
            
            //pnlImage.removeAllComponents();
            //pnlImage.addComponent(image2ClickableLabel(sFileName, 50));
         }
      });

      
      
      upload.addListener(new Upload.FailedListener(){
         private static final long serialVersionUID = 3536909203900982601L;

         public void uploadFailed(FailedEvent event){
//            table.getApplication().getMainWindow().showNotification(
//                     "ERROR",
//                     event.getSource().toString(),
//                     Notification.TYPE_WARNING_MESSAGE);
            
            upload.setEnabled(true);
         }
      });

      
      
      upload.addListener(new Upload.FinishedListener(){
         private static final long serialVersionUID = 1031302920470671299L;

         public void uploadFinished(FinishedEvent event){
            upload.setEnabled(true);
         }
      });        
     
      
      HorizontalLayout layH= new HorizontalLayout();
      
      upload.setEnabled(false);
      layH.addComponent(upload);
      
      layH.addComponent(sizeX(5));
      pnlImage.setStyleName(Runo.PANEL_LIGHT);
      
      layH.addComponent(pnlImage);
     
      this.addComponent(layH);
      
   }
   
   

   
   
   
   
   
   private class Uploader implements Upload.SucceededListener,
                                     Upload.FailedListener,
                                     Upload.Receiver,
                                     Upload.FinishedListener{

      private static final long serialVersionUID = 1420577175001384829L;





      public OutputStream receiveUpload(String filename, String MIMEType){
         String sFileExtension;
         
         try{
            String[] arrstrFileName = filename.split("\\."); 
            sFileExtension = arrstrFileName[arrstrFileName.length - 1].trim();
         }
         catch (Exception e1){
            table.getApplication().getMainWindow().showNotification(
               "ERROR",
               "Имя файла должно содержать расширение",
               Notification.TYPE_WARNING_MESSAGE
            );
            
            throw new Error("Имя файла должно содержать расширение");
         }
         
         sFileName = MongoService.getUniqueID(MImage.class)
                     + "."
                     + sFileExtension; 
         
         String sPath = ServerConstants.getImageFolder() + sFileName; 
         

         FileOutputStream fileOutputStream;
         try{
            fileOutputStream = new FileOutputStream(sPath);
            return fileOutputStream;
         }
         catch (FileNotFoundException e){
            throw new Error("Не могу загрузить файл", e);
         }
      }





      public void uploadFailed(FailedEvent event){
      }
      public void uploadSucceeded(SucceededEvent event){
      }
      public void uploadFinished(FinishedEvent event){
      }
   }

   



   @Override
   public void changeFocus(){
      if(table.getValue() == null){
         upload.setEnabled(false);
      }
      else{
         upload.setEnabled(true);
      }
   }
}
