/*
 * WANDORA
 * Knowledge Extraction, Management, and Publishing Application
 * http://wandora.org
 *
 * Copyright (C) 2004-2016 Wandora Team
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * 
 * NYTExtractorUI.java
 *
 * Created on Apr 14, 2012, 9:43:48 PM
 */

package org.wandora.application.tools.extractors.nyt;

import java.awt.Component;
import java.net.URLEncoder;
import java.util.ArrayList;
import javax.swing.JDialog;
import javax.swing.ListModel;
import org.wandora.application.Wandora;
import org.wandora.application.WandoraTool;
import org.wandora.application.contexts.Context;
import org.wandora.application.gui.UIBox;
import org.wandora.application.gui.WandoraOptionPane;
import org.wandora.application.gui.simple.SimpleButton;
import org.wandora.application.gui.simple.SimpleField;
import org.wandora.application.gui.simple.SimpleLabel;
import org.wandora.application.gui.simple.SimpleList;
import org.wandora.application.gui.simple.SimpleTabbedPane;
import org.wandora.application.tools.extractors.AbstractExtractor;

/**
 *
 * @author akivela
 */


public class NYTExtractorUI extends javax.swing.JPanel {

    private Wandora wandora = null;
    private boolean accepted = false;
    private JDialog dialog = null;
    private Context context = null;

    private static final String NYT_API_BASE = "http://api.nytimes.com/svc/search/v1/";
    private static final String NYT_API_EVENT_BASE = "http://api.nytimes.com/svc/events/v2/listings.json";
    
    
    /** Creates new form NYTExtractorUI */
    public NYTExtractorUI() {
        initComponents();
    }

    

    public boolean wasAccepted() {
        return accepted;
    }
    public void setAccepted(boolean b) {
        accepted = b;
    }

    public void open(Wandora w, Context c) {
        context = c;
        accepted = false;
        dialog = new JDialog(w, true);
        dialog.setSize(550,500);
        dialog.add(this);
        dialog.setTitle("New York Times API extractor");
        UIBox.centerWindow(dialog, w);
        if(apikey == null) {
            forgetButton.setEnabled(false);
        }
        else {
            forgetButton.setEnabled(true);
        }
        dialog.setVisible(true);
    }

    
    
    
    
    public WandoraTool[] getExtractors(NYTExtractor tool) {
        Component component = eventSearchPanel.getSelectedComponent();
        WandoraTool wt = null;
        ArrayList<WandoraTool> wts = new ArrayList();
        
        // ***** SEARCH ARTICLES *****
        if(articleSearchPanel.equals(component)) {
            String query = searchQueryTextField.getText();
            String key = solveAPIKey();
            String extractUrl = NYT_API_BASE+"article?query="+urlEncode(query)+"&api-key="+key;
            
            String facets = facetsTextField.getText().trim();
            if(facets != null && facets.length() > 0) {
                extractUrl += "&facets="+urlEncode(facets);
            }
            
            int[] fieldIndexes = fieldsList.getSelectedIndices();
            ListModel listModel = fieldsList.getModel();
            StringBuilder fieldValues = new StringBuilder("");
            for(int i=0; i<fieldIndexes.length; i++) {
                if(i>0) fieldValues.append(",");
                fieldValues.append(listModel.getElementAt(fieldIndexes[i]));
            }
            if(fieldValues.length() > 0) {
                extractUrl += "&fields="+urlEncode("url,"+fieldValues.toString());
            }
            
            String beginDate = beginDateTextField.getText().trim();
            if(beginDate != null && beginDate.length() > 0) {
                extractUrl += "&begin_date="+urlEncode(beginDate);
            }
            String endDate = endDateTextField.getText().trim();
            if(endDate != null && endDate.length() > 0) {
                extractUrl += "&end_date="+urlEncode(endDate);
            }
            String offset = offsetTextField.getText().trim();
            if(offset == null || offset.length() == 0) offset = "0";
            extractUrl += "&offset="+urlEncode(offset);

            String rank = rankComboBox.getSelectedItem().toString();
            if(rank != null && rank.length() > 0) {
                extractUrl += "&rank="+urlEncode(rank);
            }
            
            System.out.println("URL: "+extractUrl);

            NYTArticleSearchExtractor ex = new NYTArticleSearchExtractor();
            ex.setForceUrls( new String[] { extractUrl } );
            wt = ex;
            wts.add( wt );
        } 
        
        //***** SEARCH EVENTS *****
        
        else if( eventSearchPanel.equals(component) ) {
            String key = solveAPIKey();
            String extractUrl = NYT_API_EVENT_BASE+"?ll=40.756146,-73.99021&api-key="+key;
            
            System.out.println("URL: "+extractUrl);
            
            NYTEventSearchExtractor ex = new NYTEventSearchExtractor();
            ex.setForceUrls(new String[] {extractUrl } );
            wt = ex;
            wts.add(wt);
        }
        
        return wts.toArray( new WandoraTool[] {} );
    }
    
    
    
    
    
    
    protected static String urlEncode(String str) {
        try {
            str = URLEncoder.encode(str, "utf-8");
        }
        catch(Exception e) {}
        return str;
    }

    
    
    
    // ------------------------------------------------------------ API-KEY ----





    private static String apikey = null;
    public String solveAPIKey(Wandora wandora) {
        return solveAPIKey();
    }
    public String solveAPIKey() {
        if(apikey == null) {
            apikey = "";
            apikey = WandoraOptionPane.showInputDialog(Wandora.getWandora(), "Please give an api-key for NYT. You can register your api-key at http://developer.nytimes.com/docs/reference/keys", apikey, "NYT api-key", WandoraOptionPane.QUESTION_MESSAGE);
            apikey = apikey.trim();
        }
        return apikey;
    }



    
    public void forgetAuthorization() {
        apikey = null;
    }


    // -------------------------------------------------------------------------
    
    
    /** 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() {
        java.awt.GridBagConstraints gridBagConstraints;

        facetsLabel = new SimpleLabel();
        facetsTextField = new SimpleField();
        eventSearchPanel = new SimpleTabbedPane();
        articleSearchPanel = new javax.swing.JPanel();
        articleSearchInnerPanel = new javax.swing.JPanel();
        searchLabel = new SimpleLabel();
        searchQueryTextField = new SimpleField();
        optionalArticleSearchFieldsPanel = new javax.swing.JPanel();
        fieldsLabel = new SimpleLabel();
        fieldsListScrollPane = new javax.swing.JScrollPane();
        fieldsList = new SimpleList();
        beginDateLabel = new SimpleLabel();
        beginDateTextField = new SimpleField();
        endDateLabel = new SimpleLabel();
        endDateTextField = new SimpleField();
        offsetLabel = new SimpleLabel();
        offsetTextField = new SimpleField();
        rankLabel = new SimpleLabel();
        rankComboBox = new javax.swing.JComboBox();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        buttonPanel = new javax.swing.JPanel();
        forgetButton = new SimpleButton();
        buttonFillerPanel = new javax.swing.JPanel();
        okButton = new SimpleButton();
        cancelButton = new SimpleButton();

        facetsLabel.setText("Facets");
        facetsLabel.setToolTipText("Comma-delimited list of up to 5 facets.");

        setLayout(new java.awt.GridBagLayout());

        articleSearchPanel.setLayout(new java.awt.GridBagLayout());

        articleSearchInnerPanel.setLayout(new java.awt.GridBagLayout());

        searchLabel.setText("Search query");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        articleSearchInnerPanel.add(searchLabel, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        articleSearchInnerPanel.add(searchQueryTextField, gridBagConstraints);

        optionalArticleSearchFieldsPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Optional params"));
        optionalArticleSearchFieldsPanel.setLayout(new java.awt.GridBagLayout());

        fieldsLabel.setText("Fields");
        fieldsLabel.setToolTipText("Comma-delimited list of fields (no limit).");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.FIRST_LINE_END;
        gridBagConstraints.insets = new java.awt.Insets(2, 0, 2, 4);
        optionalArticleSearchFieldsPanel.add(fieldsLabel, gridBagConstraints);

        fieldsListScrollPane.setMinimumSize(new java.awt.Dimension(23, 150));
        fieldsListScrollPane.setPreferredSize(new java.awt.Dimension(125, 150));

        fieldsList.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "abstract", "author", "body", "byline", "classifiers_facet", "column_facet", "date", "dbpedia_resource_url", "des_facet", "geo_facet", "lead_paragraph", "material_type_facet", "org_facet", "per_facet", "source_facet", "title" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        fieldsListScrollPane.setViewportView(fieldsList);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 0);
        optionalArticleSearchFieldsPanel.add(fieldsListScrollPane, gridBagConstraints);

        beginDateLabel.setText("Begin date (YYYYMMDD)");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 4);
        optionalArticleSearchFieldsPanel.add(beginDateLabel, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 0);
        optionalArticleSearchFieldsPanel.add(beginDateTextField, gridBagConstraints);

        endDateLabel.setText("End date (YYYYMMDD)");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 4);
        optionalArticleSearchFieldsPanel.add(endDateLabel, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 0);
        optionalArticleSearchFieldsPanel.add(endDateTextField, gridBagConstraints);

        offsetLabel.setText("Offset");
        offsetLabel.setToolTipText("The value of offset corresponds to a set of 10 results.");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 4);
        optionalArticleSearchFieldsPanel.add(offsetLabel, gridBagConstraints);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 2, 0);
        optionalArticleSearchFieldsPanel.add(offsetTextField, gridBagConstraints);

        rankLabel.setText("Rank");
        rankLabel.setToolTipText("Use the rank parameter to set the order of the results. The default rank is newest.");
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_END;
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 4);
        optionalArticleSearchFieldsPanel.add(rankLabel, gridBagConstraints);

        rankComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "newest", "oldest", "closest" }));
        rankComboBox.setMinimumSize(new java.awt.Dimension(120, 20));
        rankComboBox.setPreferredSize(new java.awt.Dimension(120, 20));
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.LINE_START;
        optionalArticleSearchFieldsPanel.add(rankComboBox, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(8, 0, 0, 0);
        articleSearchInnerPanel.add(optionalArticleSearchFieldsPanel, gridBagConstraints);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(4, 4, 4, 4);
        articleSearchPanel.add(articleSearchInnerPanel, gridBagConstraints);

        eventSearchPanel.addTab("Article search", articleSearchPanel);
        eventSearchPanel.addTab("Event search", jTabbedPane1);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        add(eventSearchPanel, gridBagConstraints);

        buttonPanel.setLayout(new java.awt.GridBagLayout());

        forgetButton.setText("Forget api-key");
        forgetButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                forgetButtonActionPerformed(evt);
            }
        });
        buttonPanel.add(forgetButton, new java.awt.GridBagConstraints());

        buttonFillerPanel.setLayout(new java.awt.GridBagLayout());
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        buttonPanel.add(buttonFillerPanel, gridBagConstraints);

        okButton.setText("Extract");
        okButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                okButtonActionPerformed(evt);
            }
        });
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.insets = new java.awt.Insets(0, 0, 0, 2);
        buttonPanel.add(okButton, gridBagConstraints);

        cancelButton.setText("Cancel");
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });
        buttonPanel.add(cancelButton, new java.awt.GridBagConstraints());

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(2, 2, 2, 2);
        add(buttonPanel, gridBagConstraints);
    }// </editor-fold>//GEN-END:initComponents

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        accepted = false;
        if(this.dialog != null) this.dialog.setVisible(false);
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
        accepted = true;
        if(this.dialog != null) this.dialog.setVisible(false);
    }//GEN-LAST:event_okButtonActionPerformed

    private void forgetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_forgetButtonActionPerformed
        apikey = null;
    }//GEN-LAST:event_forgetButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel articleSearchInnerPanel;
    private javax.swing.JPanel articleSearchPanel;
    private javax.swing.JLabel beginDateLabel;
    private javax.swing.JTextField beginDateTextField;
    private javax.swing.JPanel buttonFillerPanel;
    private javax.swing.JPanel buttonPanel;
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel endDateLabel;
    private javax.swing.JTextField endDateTextField;
    private javax.swing.JTabbedPane eventSearchPanel;
    private javax.swing.JLabel facetsLabel;
    private javax.swing.JTextField facetsTextField;
    private javax.swing.JLabel fieldsLabel;
    private javax.swing.JList fieldsList;
    private javax.swing.JScrollPane fieldsListScrollPane;
    private javax.swing.JButton forgetButton;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JLabel offsetLabel;
    private javax.swing.JTextField offsetTextField;
    private javax.swing.JButton okButton;
    private javax.swing.JPanel optionalArticleSearchFieldsPanel;
    private javax.swing.JComboBox rankComboBox;
    private javax.swing.JLabel rankLabel;
    private javax.swing.JLabel searchLabel;
    private javax.swing.JTextField searchQueryTextField;
    // End of variables declaration//GEN-END:variables
}
