package kz.cafe.admin;

import java.util.*;
import org.vaadin.artur.icepush.*;
import kz.cafe.admin.autoimport.*;
import kz.cafe.admin.constants.*;
import kz.cafe.admin.notifications.*;
import kz.cafe.admin.panels.*;
import kz.cafe.constants.*;
import kz.cafe.db.model.*;
import com.vaadin.*;
import com.vaadin.ui.*;
import com.vaadin.ui.MenuBar.Command;
import com.vaadin.ui.MenuBar.MenuItem;



@SuppressWarnings("rawtypes")
public class AdminMain extends Application{
   private static final long serialVersionUID = 6308756539111898373L;
   
   public final ICEPush pusher = new ICEPush();

   private final Window mainWindow = new Window("BonMenu");
   
   public MenuBar menubar = new MenuBar();
   
   public AbstractPanel COMPONENT = null;
   
   
   public volatile InterfaceConstants.LANGS lang;    

   public int UID = -1;
   public boolean isAdmin;
   public Set<Integer> screenRead;
   public Set<Integer> screenAdd;
   public Set<Integer> screenEdit;
   public Set<Integer> screenDelete;
   
   
   public final Map<Integer, MenuElement> mapMenuID = new LinkedHashMap<Integer, MenuElement>();
   public final Map<Class, MenuElement>   mapMenuClass = new HashMap<Class, MenuElement>();
   
   
   private final Label lbCurentMenuItem = new Label("");
   
   

   @Override
   public void init(){
      this.setTheme("custom");
      
      AbstractLayout panelLayout = (AbstractLayout) mainWindow.getContent();
      panelLayout.setMargin(false);
      setMainWindow(mainWindow);
      
      mainWindow.addComponent(pusher);
      
      addLogo();      
      
      mainWindow.addComponent(new LoginPage(this));
      
      Notificator notificator = new Notificator(this);
      notificator.start();
   }
   

   

   public void buildMenu(){

      
      DBListPanel panelOpenFirst;
      
      
      MenuElement me = new MenuElement();
      me.ID = 0;
      me.name = "Все заведения";
      me.group = "Мои заведения";
      me.abstractTab = new TabCafe(this, getModes(me.ID));
      mapMenuClass.put(MCafe.class, me);
      mapMenuID.put(me.ID, me);
      
      panelOpenFirst = me.abstractTab.build();
      panelOpenFirst.MENU_TITLE = me.name;
      panelOpenFirst.reload();
      
      

      
      me = new MenuElement();
      me.ID = 1;
      me.name = "Изображения";
      me.group = "Мои заведения";
      me.abstractTab = new TabImages(this, getModes(me.ID));
      mapMenuClass.put(MCafeImage.class, me);
      mapMenuID.put(me.ID, me);
      
      
      
      
      me = new MenuElement();
      me.ID = 2;
      me.name = "Города";
      me.group = "Мои заведения";
      me.abstractTab = new TabCity(this, getModes(me.ID));
      mapMenuClass.put(MCity.class, me);
      mapMenuID.put(me.ID, me);
      
      
      
      
      me = new MenuElement();
      me.ID = 3;
      me.name = "Тип заведения";
      me.group = "Мои заведения";
      me.abstractTab = new TabCafeType(this, getModes(me.ID));
      mapMenuClass.put(MCafeType.class, me);
      mapMenuID.put(me.ID, me);
      
      
      me = new MenuElement();
      me.ID = 4;
      me.name = "Вид сервиса";
      me.group = "Мои заведения";
      me.abstractTab = new TabServiceType(this, getModes(me.ID));
      mapMenuClass.put(MServiceType.class, me);
      mapMenuID.put(me.ID, me);
      

      me = new MenuElement();
      me.ID = 5;
      me.name = "Требования";
      me.group = "Мои заведения";
      me.abstractTab = new TabFaceControl(this, getModes(me.ID));
      mapMenuClass.put(MServiceType.class, me);
      mapMenuID.put(me.ID, me);
      
      
      me = new MenuElement();
      me.ID = 6;
      me.name = "Кухни Мира";
      me.group = "Мои заведения";
      me.abstractTab = new TabCuisine(this, getModes(me.ID));
      mapMenuClass.put(MCuisine.class, me);
      mapMenuID.put(me.ID, me);
      
      
      
      
      
      
      me = new MenuElement();
      me.ID = 10;
      me.name = "Всё Меню";
      me.group = "Меню";
      me.abstractTab = new TabCourse(this, getModes(me.ID));
      mapMenuClass.put(MCourse.class, me);
      mapMenuID.put(me.ID, me);
      
      me = new MenuElement();
      me.ID = 11;
      me.name = "Категории меню";
      me.group = "Меню";
      me.abstractTab = new TabCourseCategory(this, getModes(me.ID));
      mapMenuClass.put(MCourseCategory.class, me);
      mapMenuID.put(me.ID, me);
      
      me = new MenuElement();
      me.ID = 12;
      me.name = "Ингредиенты";
      me.group = "Меню";
      me.abstractTab = new TabIngredient(this, getModes(me.ID));
      mapMenuClass.put(MIngredient.class, me);
      mapMenuID.put(me.ID, me);
      

      
      
      
      me = new MenuElement();
      me.ID = 20;
      me.name = "Отзывы";
      me.group = null;
      me.abstractTab = new TabFeedback(this, getModes(me.ID));
      mapMenuClass.put(MFeedback.class, me);
      mapMenuID.put(me.ID, me);
      
      
      
      
      
      me = new MenuElement();
      me.ID = 30;
      me.name = "Акции";
      me.group = null;
      me.abstractTab = new TabSales(this, getModes(me.ID));
      mapMenuClass.put(MSale.class, me);
      mapMenuID.put(me.ID, me);
      
      
      
      me = new MenuElement();
      me.ID = 31;
      me.name = "Новости";
      me.group = null;
      me.abstractTab = new TabNews(this, getModes(me.ID));
      mapMenuClass.put(MNews.class, me);
      mapMenuID.put(me.ID, me);
      
      

      
      me = new MenuElement();
      me.ID = 40;
      me.name = "Бронь";
      me.group = null;
      me.abstractTab = new TabReservation(this, getModes(me.ID));
      mapMenuClass.put(MReservation.class, me);
      mapMenuID.put(me.ID, me);
      

      me = new MenuElement();
      me.ID = 41;
      me.name = "Заказы";
      me.group = null;
      me.abstractTab = new TabOrders(this, getModes(me.ID));
      mapMenuClass.put(MOrder.class, me);
      mapMenuID.put(me.ID, me);
      

      
      
      
      me = new MenuElement();
      me.ID = 50;
      me.name = "Журнал Работы";
      me.group = null;
      me.abstractTab = new TabLog(this, getModes(me.ID));
      mapMenuClass.put(MOrder.class, me);
      mapMenuID.put(me.ID, me);
      
      
      
      
      me = new MenuElement();
      me.ID = 60;
      me.name = "Полезные номера";
      me.group = null;
      me.abstractTab = new TabPhones(this, getModes(me.ID));
      mapMenuClass.put(MPhone.class, me);
      mapMenuID.put(me.ID, me);
      
      
      
      
      
      
      me = new MenuElement();
      me.ID = 70;
      me.name = "По датам";
      me.group = "Статистика";
      me.abstractTab = new TabStatisticsDate(this, getModes(me.ID));
      mapMenuClass.put(MPhone.class, me);
      mapMenuID.put(me.ID, me);
      
      me = new MenuElement();
      me.ID = 71;
      me.name = "По IP";
      me.group = "Статистика";
      me.abstractTab = new TabStatisticsIP(this, getModes(me.ID));
      mapMenuClass.put(MPhone.class, me);
      mapMenuID.put(me.ID, me);
      

      
      me = new MenuElement();
      me.ID = 80;
      me.name = "Приложение";
      me.group = "Обратная связь";
      me.abstractTab = new TabMessageSystem(this, getModes(me.ID));
      mapMenuClass.put(MMessageSystem.class, me);
      mapMenuID.put(me.ID, me);
      
      me = new MenuElement();
      me.ID = 81;
      me.name = "По объектам";
      me.group = "Обратная связь";
      me.abstractTab = new TabMessageCafe(this, getModes(me.ID));
      mapMenuClass.put(MMessageCafe.class, me);
      mapMenuID.put(me.ID, me);
      
      
      

      
      me = new MenuElement();
      me.ID = 100;
      me.name = "Клиенты";
      me.group = "Пользователи";
      me.abstractTab = new TabUserClients(this, getModes(me.ID));
      mapMenuClass.put(MUser.class, me);
      mapMenuID.put(me.ID, me);
      
      me = new MenuElement();
      me.ID = 101;
      me.name = "Администраторы";
      me.group = "Пользователи";
      me.abstractTab = new TabUserAdmins(this, getModes(me.ID));
      mapMenuClass.put(MUser.class, me);
      mapMenuID.put(me.ID, me);
      
      MenuElement meRoleRead = new MenuElement();
      meRoleRead.ID = 102;
      meRoleRead.name = "Доступ: чтение";
      meRoleRead.group = "Пользователи";
      meRoleRead.abstractTab = new TabRoleRead(this, getModes(me.ID));
      mapMenuClass.put(MRole.class, meRoleRead);
      mapMenuID.put(meRoleRead.ID, meRoleRead);
      
      MenuElement meRoleWrite = new MenuElement();
      meRoleWrite.ID = 103;
      meRoleWrite.name = "Доступ: изменение";
      meRoleWrite.group = "Пользователи";
      meRoleWrite.abstractTab = new TabRoleEdit(this, getModes(me.ID));
      mapMenuClass.put(MRole.class, meRoleWrite);
      mapMenuID.put(meRoleWrite.ID, meRoleWrite);
      
      
      MenuElement meRoleAdd = new MenuElement();
      meRoleAdd.ID = 104;
      meRoleAdd.name = "Доступ: добавление";
      meRoleAdd.group = "Пользователи";
      meRoleAdd.abstractTab = new TabRoleAdd(this, getModes(me.ID));
      mapMenuClass.put(MRole.class, meRoleAdd);
      mapMenuID.put(meRoleAdd.ID, meRoleAdd);
      
      
      
      MenuElement meRoleDelete = new MenuElement();
      meRoleDelete.ID = 105;
      meRoleDelete.name = "Доступ: удаление";
      meRoleDelete.group = "Пользователи";
      meRoleDelete.abstractTab = new TabRoleDelete(this, getModes(me.ID));
      mapMenuClass.put(MRole.class, meRoleDelete);
      mapMenuID.put(meRoleDelete.ID, meRoleDelete);
      
      

      
      
      if(isAdmin){
         me = new MenuElement();
         me.ID = 110;
         me.name = "Клиента";
         me.group = "Сообщения";
         me.abstractTab = new TabI18NClient(this, getModesAll());
         mapMenuClass.put(MI18NClient.class, me);
         mapMenuID.put(me.ID, me);
      }
      
      
      
      
      
      
      
      
//      WebApplicationContext context = ((WebApplicationContext) getContext());
//      WebBrowser wb = context.getBrowser();

      //System.out.println(wb.getScreenHeight());
      //System.out.println(wb.getScreenWidth());      
      
      
      
      for(int ID : mapMenuID.keySet()){
         MenuElement menuElement = mapMenuID.get(ID);
         
         if(menuElement.group == null){
            if(isMenuVisible(menuElement)) {
               menubar.addItem(menuElement.name, new CustomCommand(menuElement.abstractTab));
            }
         }
         else{
            MenuBar.MenuItem menu = null;
            for(MenuItem menuItem : menubar.getItems()){
               if(menuElement.group.equals(menuItem.getText())){
                  menu = menuItem;
                  break;
               }
            }
            
            if(isMenuVisible(menuElement)) {
               if(menu == null){
                  menu = menubar.addItem(menuElement.group, null);
               }
            
               menu.addItem(menuElement.name, new CustomCommand(menuElement.abstractTab));
            }
         }
      }

      

      if(isAdmin){
         menubar.addItem("Импорт", new Command(){
            private static final long serialVersionUID = -2989038667522333813L;
   
            @Override
            public void menuSelected(MenuItem selectedItem){
               mainWindow.removeComponent(COMPONENT);
               
               TabAutoImport pnlUpload = new TabAutoImport(AdminMain.this);
               mainWindow.addComponent(pnlUpload);
               COMPONENT = pnlUpload; 
            }
         });
      }
      
      
      
      menubar.addItem("Выход", new Command(){
         private static final long serialVersionUID = -2989038667522333813L;

         @Override
         public void menuSelected(MenuItem selectedItem){
            AdminMain.this.close();
         }
      });
      
      menubar.getItems().get(0).setStyleName("selected");

      
      
      menubar.setWidth("100%");
      menubar.addStyleName("mybarmenu");      
      
      mainWindow.addComponent(menubar);


      
      COMPONENT = panelOpenFirst;       
      mainWindow.addComponent(COMPONENT);
   }
   
   

   
   
   private class CustomCommand implements Command{
      private static final long serialVersionUID = 3097467677187822222L;
      
      private AbstractTab abstractTab;

      public CustomCommand(AbstractTab abstractTab){
         super();
         this.abstractTab = abstractTab;
      }





      @Override
      public void menuSelected(MenuItem selectedItem){
         try{
            mainWindow.removeComponent(COMPONENT);
         }
         catch (Throwable e){
         }

         if (lang == null){
            lang = InterfaceConstants.LANGS.values()[0]; 
         }
         
         DBListPanel panel = abstractTab.build();
         
         panel.CURRENT_LANG.select(lang);
         
         lbCurentMenuItem.setValue(selectedItem.getText());
         
         panel.reload();
         panel.itemId = null;
         
         COMPONENT = panel;
         mainWindow.addComponent(COMPONENT);
         
         for(MenuItem menuItem : menubar.getItems()) {
            menuItem.setStyleName(null);
         }
         
         try{
            selectedItem.getParent().setStyleName("selected");
         }
         catch (Exception e){
         }
      }
   }
   
   
   
   
   
   
   private void addLogo(){
      HorizontalLayout layH = new HorizontalLayout();
      layH.setWidth("100%");
      layH.setStyleName("red-background");
      
      Label lbLogo = new Label("<div style='background-color:#E41B23;padding-top:4px;height:40px'><img src=\"" + ServerConstants.getImageURL() + "logo.png\"/></div>", Label.CONTENT_XHTML);
      lbLogo.setSizeUndefined();
      layH.addComponent(lbLogo);
      

      Label lbSpacer = new Label(" ");
      lbSpacer.setSizeFull();
      layH.addComponent(lbSpacer);
      
      
      lbCurentMenuItem.setSizeUndefined();
      lbCurentMenuItem.setStyleName("top-menu-current-item");
      layH.addComponent(lbCurentMenuItem);
      

      
      layH.setExpandRatio(lbCurentMenuItem, 0.1f);
      layH.setExpandRatio(lbSpacer, 2.0f);
      
      
      mainWindow.addComponent(layH);
   }
   
   

   
   
   public static class MenuElement implements java.io.Serializable{
      private static final long serialVersionUID = 1892399436800669025L;
      
      public int ID;
      public String group;
      public String name;
      public boolean writable;
      public AbstractTab abstractTab; 
   }
   
   


   
   
   private boolean isMenuVisible(MenuElement menuElement){
      if(isAdmin){
         return true;
      }
      else if(screenAdd.contains(menuElement.ID)){
         return true;
      }
      else if(screenRead.contains(menuElement.ID)){
         return true;
      }
      else if(screenDelete.contains(menuElement.ID)){
         return true;
      }
      else{
         return false;
      }
   }
//   
//   
//
//
//   private DBListPanel choseMenuPanel(MenuElement menuElement){
//      Set<ViewConstants.EditMode> setMode = new HashSet<ViewConstants.EditMode>();
//      
//      if(isAdmin || screenAdd.contains(menuElement.ID)){
//         setMode.add(ViewConstants.EditMode.ADD);
//      }
//      if(isAdmin || screenDelete.contains(menuElement.ID)){
//         setMode.add(ViewConstants.EditMode.DELETE);
//      }
//      if(isAdmin || screenEdit.contains(menuElement.ID)){
//         setMode.add(ViewConstants.EditMode.CHANGE);
//      }
//      
//      return menuElement.builder.build(this, setMode);
//   }
   
   
   
   private Set<AccessConstants.EditMode> getModes(int iMenu){
      Set<AccessConstants.EditMode> setMode = new HashSet<AccessConstants.EditMode>();

      if(isAdmin || screenAdd.contains(iMenu)){
         setMode.add(AccessConstants.EditMode.ADD);
      }
      if(isAdmin || screenDelete.contains(iMenu)){
         setMode.add(AccessConstants.EditMode.DELETE);
      }
      if(isAdmin || screenEdit.contains(iMenu)){
         setMode.add(AccessConstants.EditMode.CHANGE);
      }

      return setMode;
   }
   @SuppressWarnings("unused")
   private Set<AccessConstants.EditMode> getModesAll(){
      Set<AccessConstants.EditMode> setMode = new HashSet<AccessConstants.EditMode>();

      setMode.add(AccessConstants.EditMode.ADD);
      setMode.add(AccessConstants.EditMode.DELETE);
      setMode.add(AccessConstants.EditMode.CHANGE);
      return setMode;
   }
   
}
