/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package sosyalmedyaapp;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author samet
 */
public class Frm_KullaniciSayfasi extends javax.swing.JFrame {

    /**
     * Creates new form Frm_KullaniciSayfasi
     */
    DefaultTableModel dtm1 = new DefaultTableModel();
    DefaultTableModel dtm2 = new DefaultTableModel();

    public Frm_KullaniciSayfasi() {
        initComponents();

        this.setTitle(Frm_Login.loginuser.getAdi() + " " + Frm_Login.loginuser.getSoyadi());
        dtm1.setColumnIdentifiers(new Object[]{"ID", "KULLANICI ADI", "ADI", "SOYADI"});
        tbl_kisiliste.setModel(dtm1);
        dtm2.setColumnIdentifiers(new Object[]{"ID", "KULLANICI ADI", "ADI", "SOYADI"});
        tbl_arkadaslistesi.setModel(dtm2);

    }
//    USER loginuser;
//    public Frm_KullaniciSayfasi( USER loginuser) {
//        initComponents();
//        this.loginuser= loginuser;
//        this.setTitle(this.loginuser.Adi+" "+this.loginuser.Soyadi);
//    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jMenu3 = new javax.swing.JMenu();
        buttonGroup1 = new javax.swing.ButtonGroup();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbl_kisiliste = new javax.swing.JTable();
        txt_kullaniciadi = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        btn_bul = new javax.swing.JButton();
        btn_ekle = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tbl_arkadaslistesi = new javax.swing.JTable();
        rbtn_arkadaslar = new javax.swing.JRadioButton();
        rbtn_arkadaslilkistek = new javax.swing.JRadioButton();
        btn_kabulet = new javax.swing.JButton();
        btn_sil = new javax.swing.JButton();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuItem1 = new javax.swing.JMenuItem();
        jMenu2 = new javax.swing.JMenu();

        jMenu3.setText("jMenu3");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("ANA SAYFA");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jTabbedPane1.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                jTabbedPane1StateChanged(evt);
            }
        });

        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        tbl_kisiliste.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(tbl_kisiliste);

        jPanel1.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 80, 469, 170));

        txt_kullaniciadi.addInputMethodListener(new java.awt.event.InputMethodListener() {
            public void caretPositionChanged(java.awt.event.InputMethodEvent evt) {
            }
            public void inputMethodTextChanged(java.awt.event.InputMethodEvent evt) {
                txt_kullaniciadiInputMethodTextChanged(evt);
            }
        });
        txt_kullaniciadi.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                txt_kullaniciadiKeyReleased(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txt_kullaniciadiKeyTyped(evt);
            }
        });
        jPanel1.add(txt_kullaniciadi, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 40, 100, -1));

        jLabel1.setText("Adı");
        jPanel1.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 40, -1, -1));

        btn_bul.setText("Bul");
        btn_bul.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_bulActionPerformed(evt);
            }
        });
        jPanel1.add(btn_bul, new org.netbeans.lib.awtextra.AbsoluteConstraints(190, 40, -1, -1));

        btn_ekle.setText("Ekle");
        btn_ekle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_ekleActionPerformed(evt);
            }
        });
        jPanel1.add(btn_ekle, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 40, -1, -1));

        jTabbedPane1.addTab("Bul", jPanel1);

        jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        tbl_arkadaslistesi.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(tbl_arkadaslistesi);

        jPanel2.add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 100, -1, 206));

        buttonGroup1.add(rbtn_arkadaslar);
        rbtn_arkadaslar.setSelected(true);
        rbtn_arkadaslar.setText("Arkadaşlar");
        rbtn_arkadaslar.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                rbtn_arkadaslarItemStateChanged(evt);
            }
        });
        jPanel2.add(rbtn_arkadaslar, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 40, -1, -1));

        buttonGroup1.add(rbtn_arkadaslilkistek);
        rbtn_arkadaslilkistek.setText("Arkadaşlık İstekleri");
        rbtn_arkadaslilkistek.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                rbtn_arkadaslilkistekItemStateChanged(evt);
            }
        });
        jPanel2.add(rbtn_arkadaslilkistek, new org.netbeans.lib.awtextra.AbsoluteConstraints(180, 40, -1, -1));

        btn_kabulet.setText("Kabul Et");
        btn_kabulet.setEnabled(false);
        btn_kabulet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_kabuletActionPerformed(evt);
            }
        });
        jPanel2.add(btn_kabulet, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 40, -1, -1));

        btn_sil.setText("Sil");
        btn_sil.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_silActionPerformed(evt);
            }
        });
        jPanel2.add(btn_sil, new org.netbeans.lib.awtextra.AbsoluteConstraints(440, 40, -1, -1));

        jTabbedPane1.addTab("Arkadaş Listesi", jPanel2);

        jMenu1.setText("İŞLEMLER");

        jMenuItem1.setText("Log Out");
        jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItem1ActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuItem1);

        jMenuBar1.add(jMenu1);

        jMenu2.setText("Edit");
        jMenuBar1.add(jMenu2);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 570, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 387, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        // TODO add your handling code here:
        Frm_Login log = new Frm_Login();
        log.setVisible(true);

    }//GEN-LAST:event_formWindowClosing

    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
        // TODO add your handling code here:
        Frm_Login.loginuser = null;
        Frm_Login log = new Frm_Login();

        log.setVisible(true);

        this.dispose();
    }//GEN-LAST:event_jMenuItem1ActionPerformed

    private void txt_kullaniciadiKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_kullaniciadiKeyTyped
        // TODO add your handling code here:


    }//GEN-LAST:event_txt_kullaniciadiKeyTyped

    private void txt_kullaniciadiInputMethodTextChanged(java.awt.event.InputMethodEvent evt) {//GEN-FIRST:event_txt_kullaniciadiInputMethodTextChanged
        // TODO add your handling code here:

    }//GEN-LAST:event_txt_kullaniciadiInputMethodTextChanged

    private void txt_kullaniciadiKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_kullaniciadiKeyReleased
        // TODO add your handling code here:

    }//GEN-LAST:event_txt_kullaniciadiKeyReleased

    private void btn_bulActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_bulActionPerformed
        // TODO add your handling code here:
        if (txt_kullaniciadi.getText().isEmpty() || txt_kullaniciadi.getText() == null) {
            return;
        }
        String ad = txt_kullaniciadi.getText();
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("SosyalMedyaAppWithDatabasePU");
        EntityManager em = emf.createEntityManager();

        Query q = em.createQuery("SELECT u FROM USER_1 u WHERE u.adi LIKE '" + ad + "%'");

        List<USER_1> liste = q.getResultList();

        dtm1.setRowCount(0);

        for (USER_1 user : liste) {

            dtm1.addRow(new Object[]{user.getId(), user.getKullaniciAdi(), user.getAdi(), user.getSoyadi()});

        }

    }//GEN-LAST:event_btn_bulActionPerformed

    private void btn_ekleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_ekleActionPerformed
        // TODO add your handling code here:
        if (tbl_kisiliste.getSelectedRow() < 0) {
            JOptionPane.showMessageDialog(rootPane, "Bir kullanıcı Seçmelisiniz");
            return;
        }
        int id = (int) dtm1.getValueAt(tbl_kisiliste.getSelectedRow(), 0);

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("SosyalMedyaAppWithDatabasePU");
        EntityManager em = emf.createEntityManager();

        Query q = em.createQuery("SELECT u FROM USER_1 u WHERE u.id=:id");
        q.setParameter("id", id);

        USER_1 gelen = (USER_1) q.getSingleResult();
        if (gelen == null) {

            return;
        }

        ARKADASLIK yeni = new ARKADASLIK();
        yeni.setId(3);
        yeni.setIdUserIstek(Frm_Login.loginuser.getId());
        yeni.setIdUserKabul(gelen.getId());
        yeni.setKabulDurumu(false);
        em.getTransaction().begin();
        em.persist(yeni);
        em.getTransaction().commit();


    }//GEN-LAST:event_btn_ekleActionPerformed

    private void jTabbedPane1StateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_jTabbedPane1StateChanged
        // TODO add your handling code here:
//        dtm2.setRowCount(0);
//        for (USER user : Frm_Login.loginuser.ArkadasListesi) {
//
//            dtm2.addRow(new Object[]{user.KullaniciAdi, user.Adi, user.Soyadi});
//
//        }

    }//GEN-LAST:event_jTabbedPane1StateChanged

    private void rbtn_arkadaslarItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_rbtn_arkadaslarItemStateChanged
        if (!rbtn_arkadaslar.isSelected()) {
            return;
        }

        btn_kabulet.setEnabled(false);

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("SosyalMedyaAppWithDatabasePU");
        EntityManager em = emf.createEntityManager();

        Query q = em.createQuery("SELECT u FROM ARKADASLIK u WHERE u.idUserKabul=:id AND u.kabulDurumu=true");
        q.setParameter("id", Frm_Login.loginuser.getId());

        List<ARKADASLIK> gelenistekler = q.getResultList();
        dtm2.setRowCount(0);
        for (ARKADASLIK istek : gelenistekler) {

            q = em.createQuery("SELECT u FROM USER_1 u WHERE u.id=:id");
            q.setParameter("id", istek.getIdUserIstek());

            USER_1 arkadas = (USER_1) q.getSingleResult();
            if (arkadas != null) {
                dtm2.addRow(new Object[]{arkadas.getId(), arkadas.getKullaniciAdi(), arkadas.getAdi(), arkadas.getSoyadi()});
                return;
            }
        }


    }//GEN-LAST:event_rbtn_arkadaslarItemStateChanged

    private void btn_kabuletActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_kabuletActionPerformed

// TODO add your handling code here:
        if (tbl_arkadaslistesi.getSelectedRow() < 0) {
            JOptionPane.showMessageDialog(rootPane, "Bir kullanıcı Seçmelisiniz");
            return;
        }

        int id = (int) dtm2.getValueAt(tbl_arkadaslistesi.getSelectedRow(), 0);

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("SosyalMedyaAppWithDatabasePU");
        EntityManager em = emf.createEntityManager();

        Query q = em.createQuery("UPDATE ARKADASLIK u SET u.kabulDurumu=true  WHERE u.idUserKabul=:kabulid AND U.idUserIstek=:istekid");
        q.setParameter("istekid", id);
        q.setParameter("kabulid", Frm_Login.loginuser.getId());

        em.getTransaction().begin();
        q.executeUpdate();
        em.getTransaction().commit();


    }//GEN-LAST:event_btn_kabuletActionPerformed

    private void rbtn_arkadaslilkistekItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_rbtn_arkadaslilkistekItemStateChanged
        // TODO add your handling code here:
        if (!rbtn_arkadaslilkistek.isSelected()) {
            return;
        }

        btn_kabulet.setEnabled(true);

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("SosyalMedyaAppWithDatabasePU");
        EntityManager em = emf.createEntityManager();

        Query q = em.createQuery("SELECT u FROM ARKADASLIK u WHERE u.idUserKabul=:id AND u.kabulDurumu=false");
        q.setParameter("id", Frm_Login.loginuser.getId());

        List<ARKADASLIK> gelenistekler = q.getResultList();
        dtm2.setRowCount(0);
        for (ARKADASLIK istek : gelenistekler) {

            q = em.createQuery("SELECT u FROM USER_1 u WHERE u.id=:id");
            q.setParameter("id", istek.getIdUserIstek());

            USER_1 arkadas = (USER_1) q.getSingleResult();
            if (arkadas != null) {
                dtm2.addRow(new Object[]{arkadas.getId(), arkadas.getKullaniciAdi(), arkadas.getAdi(), arkadas.getSoyadi()});
                return;
            }
        }


    }//GEN-LAST:event_rbtn_arkadaslilkistekItemStateChanged

    private void btn_silActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_silActionPerformed
        // TODO add your handling code here:
        if (tbl_arkadaslistesi.getSelectedRow() < 0) {
            JOptionPane.showMessageDialog(rootPane, "Bir kullanıcı Seçmelisiniz");
            return;
        }

        int id = (int) dtm2.getValueAt(tbl_arkadaslistesi.getSelectedRow(), 0);

        EntityManagerFactory emf = Persistence.createEntityManagerFactory("SosyalMedyaAppWithDatabasePU");
        EntityManager em = emf.createEntityManager();

        Query q = em.createQuery("DELETE FROM ARKADASLIK u WHERE u.idUserKabul=:kabulid AND U.idUserIstek=:istekid");
        q.setParameter("istekid", id);
        q.setParameter("kabulid", Frm_Login.loginuser.getId());

        em.getTransaction().begin();
        q.executeUpdate();
        em.getTransaction().commit();
        
        
    }//GEN-LAST:event_btn_silActionPerformed

    /**
     * @param args the command line arguments
     */
//    public static void main(String args[]) {
//        /* Set the Nimbus look and feel */
//        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
//        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
//         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
//         */
//        try {
//            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
//                if ("Nimbus".equals(info.getName())) {
//                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
//                    break;
//                }
//            }
//        } catch (ClassNotFoundException ex) {
//            java.util.logging.Logger.getLogger(Frm_KullaniciSayfasi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (InstantiationException ex) {
//            java.util.logging.Logger.getLogger(Frm_KullaniciSayfasi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (IllegalAccessException ex) {
//            java.util.logging.Logger.getLogger(Frm_KullaniciSayfasi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
//            java.util.logging.Logger.getLogger(Frm_KullaniciSayfasi.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
//        }
//        //</editor-fold>
//
//        /* Create and display the form */
//        java.awt.EventQueue.invokeLater(new Runnable() {
//            public void run() {
//                new Frm_KullaniciSayfasi().setVisible(true);
//            }
//        });
//    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_bul;
    private javax.swing.JButton btn_ekle;
    private javax.swing.JButton btn_kabulet;
    private javax.swing.JButton btn_sil;
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenu jMenu2;
    private javax.swing.JMenu jMenu3;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenuItem jMenuItem1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JRadioButton rbtn_arkadaslar;
    private javax.swing.JRadioButton rbtn_arkadaslilkistek;
    private javax.swing.JTable tbl_arkadaslistesi;
    private javax.swing.JTable tbl_kisiliste;
    private javax.swing.JTextField txt_kullaniciadi;
    // End of variables declaration//GEN-END:variables
}