package net.minecraft.launcher.ui.popups.login;

import com.mojang.authlib.Agent;
import com.mojang.authlib.GameProfile;
import com.mojang.authlib.UserAuthentication;
import com.mojang.authlib.exceptions.AuthenticationException;
import com.mojang.authlib.exceptions.InvalidCredentialsException;
import com.mojang.authlib.exceptions.UserMigratedException;
import com.mojang.util.UUIDTypeAdapter;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import net.mc.main.Main;
import net.miginfocom.swing.MigLayout;
import net.minecraft.launcher.Language;
import net.minecraft.launcher.Launcher;
import net.minecraft.launcher.profile.AuthenticationDatabase;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class LogInForm extends JPanel implements ActionListener {
   private static final Logger LOGGER = LogManager.getLogger();
   private final LogInPopup popup;
   private final JTextField usernameField = new JTextField();
   private final JPasswordField passwordField = new JPasswordField();
   private final JComboBox userDropdown = new JComboBox();
   private final JPanel userDropdownPanel = new JPanel();
   private final UserAuthentication authentication;
   private final JComboBox langDropdown = new JComboBox();
   private final JButton addUser = new JButton(Language.get("login.tab.main.save"));
   private final JButton removeUser = new JButton(Language.get("login.tab.main.delete"));
   private final JButton playButton1 = new JButton(Language.get("login.tab.main.play"));
   private final JCheckBox autologin = new JCheckBox(Language.get("login.tab.options.auto"));
   private final JCheckBox syncLanguage = new JCheckBox(Language.get("login.tab.options.autolang"));
   private final JCheckBox darkTheme = new JCheckBox("Dark Theme");
   private final JButton saveOptions = new JButton(Language.get("button.save"));
   private Map<String, ComboItem> langItems = new HashMap();

   public LogInForm(LogInPopup popup) {
      this.popup = popup;
      this.authentication = popup.getMinecraftLauncher().getProfileManager().getAuthDatabase().getAuthenticationService().createUserAuthentication(Agent.MINECRAFT);
      this.usernameField.addActionListener(this);
      this.passwordField.addActionListener(this);
      this.usernameField.addActionListener(this);
      this.addUser.addActionListener(this);
      this.removeUser.addActionListener(this);
      this.userDropdown.addActionListener(this);
      this.playButton1.addActionListener(this);
      this.autologin.addActionListener(this);
      this.syncLanguage.addActionListener(this);
      this.darkTheme.addActionListener(this);
      this.langDropdown.addActionListener(this);
      this.saveOptions.addActionListener(this);
      this.langItems.put("en", new ComboItem("en", (String)Language.langs.get("en")));
      this.langItems.put("ea", new ComboItem("ea", (String)Language.langs.get("ea")));
      this.langItems.put("cs", new ComboItem("cs", (String)Language.langs.get("cs")));
      this.langItems.put("es", new ComboItem("es", (String)Language.langs.get("es")));
      this.langItems.put("fi", new ComboItem("fi", (String)Language.langs.get("fi")));
      this.langItems.put("pl", new ComboItem("pl", (String)Language.langs.get("pl")));
      this.langItems.put("pt", new ComboItem("pt", (String)Language.langs.get("pt")));
      this.langItems.put("tr", new ComboItem("tr", (String)Language.langs.get("tr")));
      this.langItems.put("vi", new ComboItem("vi", (String)Language.langs.get("vi")));
      this.langItems.put("de", new ComboItem("de", (String)Language.langs.get("de")));
      this.langItems.put("it", new ComboItem("it", (String)Language.langs.get("it")));
      this.langItems.put("fr", new ComboItem("fr", (String)Language.langs.get("fr")));
      this.langItems.put("ru", new ComboItem("ru", (String)Language.langs.get("ru")));
      this.langItems.put("hu", new ComboItem("hu", (String)Language.langs.get("hu")));
      this.langItems.put("et", new ComboItem("et", (String)Language.langs.get("et")));
      this.langItems.put("tl", new ComboItem("tl", (String)Language.langs.get("tl")));
      this.langItems.put("hr", new ComboItem("hr", (String)Language.langs.get("hr")));
      this.langItems.put("th", new ComboItem("th", (String)Language.langs.get("th")));
      this.langItems.put("nl", new ComboItem("nl", (String)Language.langs.get("nl")));
      this.langDropdown.addItem(this.langItems.get("en"));
      this.langDropdown.addItem(this.langItems.get("ea"));
      this.langDropdown.addItem(this.langItems.get("cs"));
      this.langDropdown.addItem(this.langItems.get("es"));
      this.langDropdown.addItem(this.langItems.get("fi"));
      this.langDropdown.addItem(this.langItems.get("pl"));
      this.langDropdown.addItem(this.langItems.get("pt"));
      this.langDropdown.addItem(this.langItems.get("tr"));
      this.langDropdown.addItem(this.langItems.get("vi"));
      this.langDropdown.addItem(this.langItems.get("de"));
      this.langDropdown.addItem(this.langItems.get("it"));
      this.langDropdown.addItem(this.langItems.get("fr"));
      this.langDropdown.addItem(this.langItems.get("ru"));
      this.langDropdown.addItem(this.langItems.get("et"));
      this.langDropdown.addItem(this.langItems.get("hu"));
      this.langDropdown.addItem(this.langItems.get("tl"));
      this.langDropdown.addItem(this.langItems.get("hr"));
      this.langDropdown.addItem(this.langItems.get("th"));
      this.langDropdown.addItem(this.langItems.get("nl"));
      this.createInterface(true);
      this.updateLDD();
      Boolean isAutoLogin = Launcher.getInstance().getUsernameManager().isAutoLogin();
      String autoLoginName = Launcher.getInstance().getUsernameManager().getAutoLoginName();
      this.syncLanguage.setSelected(Launcher.getInstance().getUsernameManager().willSyncLanguage());
      this.darkTheme.setSelected(Launcher.getInstance().getUsernameManager().getDark());
      System.out.println(isAutoLogin + " " + autoLoginName);
   }

   private void updateLDD() {
      String lang = Language.getLanguage();
      ComboItem item = (ComboItem)this.langItems.get(lang);
      this.langDropdown.setSelectedItem(item);
   }

   private void createInterface(Boolean visible) {
      System.out.println("CREATING INTERFACE");
      this.setLayout(new GridLayout());
      JTabbedPane tabbedPane = new JTabbedPane();
      JComponent panel1 = this.makeMainPanel();
      tabbedPane.addTab(Language.get("login.tab.main"), panel1);
      JComponent panel2 = this.makeOptionPanel();
      tabbedPane.addTab(Language.get("login.tab.options"), panel2);
      this.add(tabbedPane);
      tabbedPane.setVisible(visible);
   }

   protected JComponent makeMainPanel() {
      System.out.println("MAKING MAIN PANEL");
      JPanel panel = new JPanel(new MigLayout("fillx", "[right]rel[grow,fill]", "[]10[]"));
      JLabel usernameLabel = new JLabel(Language.get("login.tab.main.title"));
      usernameLabel.setFont(new Font(UIManager.getDefaults().getFont("TabbedPane.font").getFontName(), 1, 14));
      usernameLabel.setHorizontalAlignment(0);
      panel.add(usernameLabel, "Wrap, grow, span");
      ((JLabel)this.userDropdown.getRenderer()).setHorizontalAlignment(0);
      this.userDropdown.setFont(new Font(UIManager.getDefaults().getFont("TabbedPane.font").getFontName(), 1, 18));
      panel.add(this.userDropdown, "span, grow, wrap");
      panel.add(this.addUser, "split 2, span ,grow");
      panel.add(this.removeUser, "wrap, span, grow");
      this.playButton1.setFont(new Font(UIManager.getDefaults().getFont("TabbedPane.font").getFontName(), 1, 20));
      panel.add(this.playButton1, "span, h 50, grow, wrap");
      this.updateDropDown();
      this.userDropdown.setSelectedItem(Launcher.getInstance().getUsernameManager().getLastUsed());
      this.popup.getErrorForm().displayError((Throwable)null, "");
      return panel;
   }

   protected JComponent makeOptionPanel() {
      System.out.println("MAKING OPTION PANEL");
      JPanel panel = new JPanel(new MigLayout("fillx", "[right]rel[grow,fill]", "[]10[]"));
      panel.add(this.autologin, "span, align center, grow, wrap");
      panel.add(this.syncLanguage, "span, align center, grow, wrap");
      panel.add(this.darkTheme, "span, align center, grow, wrap");
      panel.add(new JLabel("Language: "));
      panel.add(this.langDropdown, "span, align center, grow, wrap");
      panel.add(this.saveOptions, "span, align center, grow");
      return panel;
   }

   public void actionPerformed(ActionEvent e) {
      Boolean selected;
      if (e.getSource() == this.syncLanguage) {
         selected = this.syncLanguage.isSelected();
         Launcher.getInstance().getUsernameManager().setSyncLanguage(selected);
      }

      if (e.getSource() == this.darkTheme) {
         selected = this.darkTheme.isSelected();
         Launcher.getInstance().getUsernameManager().setDark(selected);
      }

      String name;
      if (e.getSource() == this.saveOptions) {
         name = ((ComboItem)this.langDropdown.getSelectedItem()).getValue();
         Language l = new Language();
         l.load(name);
         this.popup.getErrorForm().displayError((Throwable)null, Language.get("login.msg.saved"));
         Launcher.getInstance().getUsernameManager().save();
         Object[] options1 = new Object[]{Language.get("button.restart"), Language.get("button.cancel")};
         JPanel panel = new JPanel();
         panel.add(new JLabel(Language.get("login.tab.options.restart.msg")));
         int result = JOptionPane.showOptionDialog((Component)null, panel, Language.get("login.tab.options.restart"), 1, -1, (Icon)null, options1, (Object)null);
         if (Launcher.getInstance().getUsernameManager().willSyncLanguage()) {
            Launcher.getInstance().getOptionsManager().setLanguage();
         }

         if (result == 0) {
            try {
               Main.restartApplication();
            } catch (IOException var10) {
               java.util.logging.Logger.getLogger(LogInForm.class.getName()).log(Level.SEVERE, (String)null, var10);
            } catch (URISyntaxException var11) {
               java.util.logging.Logger.getLogger(LogInForm.class.getName()).log(Level.SEVERE, (String)null, var11);
            }
         }
      }

      if (e.getSource() == this.langDropdown) {
         name = ((ComboItem)this.langDropdown.getSelectedItem()).getValue();
         Launcher.getInstance().getUsernameManager().setLanguage(name);
         System.out.println("POINT5");
      }

      if (e.getSource() == this.autologin) {
         name = this.userDropdown.getEditor().getItem().toString();
         if (name.equals("")) {
            this.autologin.setSelected(false);
         } else if (this.autologin.isSelected()) {
            this.popup.getErrorForm().displayError((Throwable)null, Language.get("login.msg.auto.1"), Language.get("login.msg.auto.2.1") + name + Language.get("login.msg.auto.2.2"), Language.get("login.msg.auto.3"));
            this.userDropdown.setEnabled(false);
            this.addUser.setEnabled(false);
            this.removeUser.setEnabled(false);
            Launcher.getInstance().getUsernameManager().setAutoLoginName(name);
            Launcher.getInstance().getUsernameManager().setAutoLogin(Boolean.TRUE);
            Launcher.getInstance().getUsernameManager().save();
            System.out.println("POINT4");
         } else {
            this.popup.getErrorForm().displayError((Throwable)null, "");
            this.userDropdown.setEnabled(true);
            this.addUser.setEnabled(true);
            this.removeUser.setEnabled(true);
            Launcher.getInstance().getUsernameManager().setAutoLoginName("");
            Launcher.getInstance().getUsernameManager().setAutoLogin(Boolean.FALSE);
            System.out.println("POINT3");
         }
      }

      if (e.getSource() == this.playButton1) {
         name = this.userDropdown.getEditor().getItem().toString();
         System.out.println("USING USERNAME: " + name);
         if (!name.equalsIgnoreCase("") && !name.isEmpty() && name.length() != 0) {
            this.popup.getErrorForm().displayError((Throwable)null, "");
            this.tryLogIn(this.userDropdown.getSelectedItem().toString());
         } else {
            this.popup.getErrorForm().displayError((Throwable)null, Language.get("login.msg.blank.1"), Language.get("login.msg.blank.2"));
         }
      }

      if (e.getSource() == this.removeUser) {
         try {
            this.popup.getErrorForm().displayError((Throwable)null, "");
            name = this.userDropdown.getEditor().getItem().toString();
            Launcher.getInstance().getUsernameManager().removeUsername(name);
            this.popup.getErrorForm().displayError((Throwable)null, "");
            this.autologin.setSelected(false);
            this.userDropdown.setEnabled(true);
            Launcher.getInstance().getUsernameManager().setAutoLoginName("");
            Launcher.getInstance().getUsernameManager().setAutoLogin(Boolean.FALSE);
            System.out.println("POINT2");
         } catch (IOException var9) {
            LOGGER.error((String)"Could not set username", (Throwable)var9);
         }

         this.updateDropDown();
      }

      if (e.getSource() == this.addUser) {
         name = this.userDropdown.getEditor().getItem().toString();
         if ("".equals(name)) {
            this.popup.getErrorForm().displayError((Throwable)null, Language.get("login.msg.blank.1"), Language.get("login.msg.blank.2"));
         } else {
            this.popup.getErrorForm().displayError((Throwable)null, "");

            try {
               Launcher.getInstance().getUsernameManager().addUsername(name);
               this.updateDropDown();
               this.userDropdown.getEditor().setItem(name);
               this.userDropdown.setSelectedItem(name);
            } catch (IOException var8) {
               LOGGER.error((String)"Could not add user", (Throwable)var8);
            }
         }
      }

   }

   private boolean updateDropDown() {
      this.userDropdown.removeAllItems();
      Integer count = 0;
      this.userDropdown.addItem("");

      for(Iterator var3 = Launcher.getInstance().getUsernameManager().getUsernames().iterator(); var3.hasNext(); count = count + 1) {
         String um = (String)var3.next();
         this.userDropdown.addItem(um);
      }

      if (count != 0) {
         this.ddpanelset(true);
         return true;
      } else {
         this.ddpanelset(false);
         return false;
      }
   }

   private void ddpanelset(Boolean bool) {
      this.userDropdown.setEditable(true);
      this.removeUser.setEnabled(bool);
   }

   public void tryLogIn(final String username) {
      System.out.println("OVER HERE 2");
      this.popup.setCanLogIn(false);
      this.authentication.logOut();
      this.authentication.setUsername(username);
      this.authentication.setPassword(String.valueOf(this.passwordField.getPassword()));
      final int passwordLength = this.passwordField.getPassword().length;
      this.passwordField.setText("");
      this.popup.getMinecraftLauncher().getLauncher().getVersionManager().getExecutorService().execute(new Runnable() {
         public void run() {
            try {
               LogInForm.this.authentication.logIn();
               AuthenticationDatabase authDatabase = LogInForm.this.popup.getMinecraftLauncher().getProfileManager().getAuthDatabase();
               if (LogInForm.this.authentication.getSelectedProfile() != null) {
                  authDatabase.register(UUIDTypeAdapter.fromUUID(LogInForm.this.authentication.getSelectedProfile().getId()), LogInForm.this.authentication);
                  LogInForm.this.popup.setLoggedIn(UUIDTypeAdapter.fromUUID(LogInForm.this.authentication.getSelectedProfile().getId()));
               } else if (!ArrayUtils.isNotEmpty((Object[])LogInForm.this.authentication.getAvailableProfiles())) {
                  String uuid = "demo-" + LogInForm.this.authentication.getUserID();
                  authDatabase.register(uuid, LogInForm.this.authentication);
                  LogInForm.this.popup.setLoggedIn(uuid);
               } else {
                  GameProfile[] var5;
                  int var4 = (var5 = LogInForm.this.authentication.getAvailableProfiles()).length;
                  int var3 = 0;

                  while(true) {
                     if (var3 >= var4) {
                        SwingUtilities.invokeLater(new Runnable() {
                           public void run() {
                              LogInForm.this.usernameField.setEditable(false);
                              LogInForm.this.passwordField.setEditable(false);
                              LogInForm.this.userDropdownPanel.setVisible(true);
                              LogInForm.this.popup.repack();
                              LogInForm.this.popup.setCanLogIn(true);
                              LogInForm.this.passwordField.setText(StringUtils.repeat('*', passwordLength));
                           }
                        });
                        break;
                     }

                     GameProfile profile = var5[var3];
                     LogInForm.this.userDropdown.addItem(profile.getName());
                     ++var3;
                  }
               }

               Launcher.getInstance().getUsernameManager().setLastUsed(username);
               Launcher.getInstance().getUsernameManager().save();
            } catch (UserMigratedException var6) {
               LogInForm.LOGGER.error((String)"Couldn't log in", (Throwable)var6);
               LogInForm.this.popup.getErrorForm().displayError(var6, "Sorry, but we can't log you in with your username.", "You have migrated your account, please use your email address.");
               LogInForm.this.popup.setCanLogIn(true);
            } catch (InvalidCredentialsException var7) {
               LogInForm.LOGGER.error((String)"Couldn't log in", (Throwable)var7);
               LogInForm.this.popup.getErrorForm().displayError(var7, "Sorry, but your username or password is incorrect!", "Please try again. If you need help, try the 'Forgot Password' link.");
               LogInForm.this.popup.setCanLogIn(true);
            } catch (AuthenticationException var8) {
               LogInForm.LOGGER.error((String)"Couldn't log in", (Throwable)var8);
               LogInForm.this.popup.getErrorForm().displayError(var8, "Sorry, but we couldn't connect to our servers.", "Please make sure that you are online and that Minecraft is not blocked.");
               LogInForm.this.popup.setCanLogIn(true);
            }

         }
      });
   }
}
