/*
 * 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 git;

import java.applet.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.geom.Rectangle2D;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import static java.awt.print.Printable.NO_SUCH_PAGE;
import static java.awt.print.Printable.PAGE_EXISTS;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import jdk.nashorn.internal.parser.JSONParser;
import org.json.*;
import jpos.JposException;
import jpos.FiscalPrinter;
import jpos.FiscalPrinterConst;
import jpos.util.JposPropertiesConst;

public class GIT extends Thread{
    
    private final String USER_AGENT = "Mozilla/5.0";
    private ArrayList<User> usersArray = null;
    private ArrayList<Integer> selectedUsers =  null;
    private String fileName = "configurations.txt";
    private String fileNameDomain = "domain.txt";
    private String fileNameIP = "ip_based.txt";
    private String domain = "http://virtualbeach.gitgrado.it";
    private boolean iPBased = true;
    private PopupMenu popup = null;
    private Menu displayMenu = null;
    
    public GIT(){
        /*FiscalPrinter printer = new FiscalPrinter();

        try
        {
           //Open Printer
           printer.open("EthernetFiscalPrinter");
           printer.claim(1);
           printer.setDeviceEnabled(true);

           printer.beginNonFiscal();
           printer.printNormal(FiscalPrinterConst.FPTR_S_RECEIPT, "Print Test Line 1");
           printer.printNormal(FiscalPrinterConst.FPTR_S_RECEIPT, "Print Test Line 2");
           printer.printNormal(FiscalPrinterConst.FPTR_S_RECEIPT, "Print Test Line 3");
           printer.printNormal(FiscalPrinterConst.FPTR_S_RECEIPT, "Print Test Line 4");
           printer.printNormal(FiscalPrinterConst.FPTR_S_RECEIPT, "Print Test Line 5");
           printer.endNonFiscal();


           printer.beginFiscalReceipt(true);
           // description price quantity, vatInfo,unitPrice,unitName
           printer.printRecItem("Articolo 1", 100, 1000, 0, 100, "");
           printer.printRecItem("Articolo 2", 100, 1000, 0, 100, "");
           printer.printRecItem("Articolo 3", 100, 1000, 0, 100, "");
           printer.printRecItem("Articolo 4", 100, 1000, 0, 100, "");
           printer.printRecItem("Articolo 5", 100, 1000, 0, 100, "");
           //total payment description
           printer.printRecTotal(500, 600, "Pagamento");
           printer.endFiscalReceipt(true);

           //Close Printer
           printer.setDeviceEnabled(false);
           printer.release();
           printer.close();
        }
        catch(JposException e)
        {
            // display any errors that come up
            e.printStackTrace();
        }
        finally
        {
            // close the printer object
            try
            {
                printer.close();
            }
            catch (Exception e) {}
        }

        System.exit(0);*/
        String lineIP = null;
        iPBased = true;
        
        try {
            // FileReader reads text files in the default encoding.
            FileReader fileReader = 
                new FileReader(fileNameIP);

            // Always wrap FileReader in BufferedReader.
            BufferedReader bufferedReader = 
                new BufferedReader(fileReader);

            while((lineIP = bufferedReader.readLine()) != null) {
                if(lineIP.length() > 0){
                    if(lineIP.equalsIgnoreCase("true")){
                        this.iPBased = true;
                    }else{
                        this.iPBased = false;
                    }
                }
                System.out.println(lineIP);
            }   

            // Always close files.
            bufferedReader.close();         
        }
        catch(FileNotFoundException ex) {
            System.out.println(
                "Unable to open file '" + 
                fileNameIP + "'");                
        }
        catch(IOException ex) {
            System.out.println(
                "Error reading file '" 
                + fileNameIP + "'");                  
            // Or we could just do this: 
            // ex.printStackTrace();
        }
                
        
        
        String lineDomain = null;

        try {
            // FileReader reads text files in the default encoding.
            FileReader fileReader = 
                new FileReader(fileNameDomain);

            // Always wrap FileReader in BufferedReader.
            BufferedReader bufferedReader = 
                new BufferedReader(fileReader);

            while((lineDomain = bufferedReader.readLine()) != null) {
                if(lineDomain.length() > 0){
                    domain = lineDomain;
                }
                System.out.println(lineDomain);
            }   

            // Always close files.
            bufferedReader.close();         
        }
        catch(FileNotFoundException ex) {
            System.out.println(
                "Unable to open file '" + 
                fileNameDomain + "'");                
        }
        catch(IOException ex) {
            System.out.println(
                "Error reading file '" 
                + fileNameDomain + "'");                  
            // Or we could just do this: 
            // ex.printStackTrace();
        }
        
        usersArray = new ArrayList<User>();
        selectedUsers = new ArrayList<Integer>();
        
        String line = null;

        try {
            // FileReader reads text files in the default encoding.
            FileReader fileReader = 
                new FileReader(fileName);

            // Always wrap FileReader in BufferedReader.
            BufferedReader bufferedReader = 
                new BufferedReader(fileReader);

            while((line = bufferedReader.readLine()) != null) {
                selectedUsers.add(new Integer(line));
                System.out.println(line);
            }   

            // Always close files.
            bufferedReader.close();         
        }
        catch(FileNotFoundException ex) {
            ex.printStackTrace();
            System.out.println(
                "Unable to open file '" + 
                fileName + "'");                
        }
        catch(IOException ex) {
            System.out.println(
                "Error reading file '" 
                + fileName + "'");                  
            // Or we could just do this: 
            // ex.printStackTrace();
        }
        
        
        if (!SystemTray.isSupported()) {
            System.out.println("SystemTray is not supported");
            return;
        }
        popup = new PopupMenu();
        final TrayIcon trayIcon = new TrayIcon(new ImageIcon(getClass().getResource("/git/bulb.gif")).getImage(), "tray icon");
        final SystemTray tray = SystemTray.getSystemTray();
        // Create a pop-up menu components
        MenuItem aboutItem = new MenuItem("About");
        aboutItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JFrame frame = new JFrame("My dialog asks....");

                frame.setUndecorated( true );
                frame.setVisible( true );
                frame.setLocationRelativeTo( null );


                String message = JOptionPane.showInputDialog(frame,
                    "Would this be enough?.", 
                    "My dialog asks....", 
                    JOptionPane.INFORMATION_MESSAGE);

                System.out.println( "Got " + message );

                frame.dispose();

            }

        });
        displayMenu = new Menu("Display");
        MenuItem exitItem = new MenuItem("Exit");
        exitItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                JFrame frame = new JFrame("My dialog asks....");

                frame.setUndecorated( true );
                frame.setVisible( true );
                frame.setLocationRelativeTo( null );
                
                
                int confirm = JOptionPane.showOptionDialog(frame,
                        "Are You Sure to Close this Application?",
                        "Exit Confirmation", JOptionPane.YES_NO_OPTION,
                        JOptionPane.QUESTION_MESSAGE, null, null, null);
                if (confirm == JOptionPane.YES_OPTION) {
                    System.exit(0);
                }

                frame.dispose();

            }

        });
        
        MenuItem refreshItem = new MenuItem("Refresh");
        refreshItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                refreshUsersList();
                refreshUsers(true);
            }

        });
        
        CheckboxMenuItem iPItem = new CheckboxMenuItem("IP Based");
        iPItem.addItemListener(new ItemListener() {
            @Override
            public void itemStateChanged(ItemEvent e) {
                System.out.println("Stato: "+((CheckboxMenuItem)e.getSource()).getState());
                if(((CheckboxMenuItem)e.getSource()).getState()){
                    iPBased = true;  
                    displayMenu.setEnabled(false);
                }else{
                    iPBased = false;
                    restoreConfiguratedUsers();
                    displayMenu.setEnabled(true);
                }
                refreshIPBased();
            }
        });
        if(this.iPBased){
            iPItem.setState(true);           
            displayMenu.setEnabled(false);
        }else{
            iPItem.setState(false);
            displayMenu.setEnabled(true);
        }
        
        //Add components to pop-up menu
        popup.addSeparator();
        popup.add(displayMenu);
        refreshUsersList();
        /*try {
            String jsonResponse = getUsersList();
            JSONArray jsonArray = (JSONArray) new JSONTokener(jsonResponse).nextValue();
            for(int i=0; i<jsonArray.length(); i++){
                System.out.println(jsonArray.getJSONObject(i).getInt("id"));
                System.out.println(jsonArray.getJSONObject(i).getString("username"));
                CheckboxMenuItem item = new CheckboxMenuItem(jsonArray.getJSONObject(i).getString("username"));
                displayMenu.add(item);
                User userTmp = new User(jsonArray.getJSONObject(i).getInt("id"), jsonArray.getJSONObject(i).getString("username"), item);
                if(selectedUsers.contains(jsonArray.getJSONObject(i).getInt("id"))){
                    popup.insert(userTmp.getMenu(), 0);
                    item.setState(true);
                    refreshUser(userTmp);
                }else{
                    userTmp.setState(false);
                }
                item.addItemListener(new ItemListener() {
                    @Override
                    public void itemStateChanged(ItemEvent e) {
                        for (User user : usersArray) {
                            if(user.getCheckboxMenuItem() == e.getSource()){
                                if(((CheckboxMenuItem)e.getSource()).getState()){
                                    refreshUser(user);
                                    popup.insert(user.getMenu(), 0);
                                    selectedUsers.add(user.getId());
                                }else{
                                    user.setState(false);
                                    selectedUsers.remove(new Integer(user.getId()));
                                    int itemsCount = popup.getItemCount();
                                    for(int i=0; i<itemsCount; i++){
                                        if(popup.getItem(i) == user.getMenu()){
                                            popup.remove(i);
                                            break;
                                        }
                                    }
                                }
                                break;
                            }
                        }
                        refreshConfiguration();
                    }
                });
                usersArray.add(userTmp);
            }
            
        } catch (Exception ex) {
            Logger.getLogger(GIT.class.getName()).log(Level.SEVERE, null, ex);
        }*/
            
            //Check the SystemTray is supported
            /*if (!SystemTray.isSupported()) {
            System.out.println("SystemTray is not supported");
            return;
            }
            final PopupMenu popup = new PopupMenu();
            final TrayIcon trayIcon = new TrayIcon(new ImageIcon("images/bulb.gif").getImage(), "tray icon");
            final SystemTray tray = SystemTray.getSystemTray();*/
            
            //refreshUsers(true);
            this.start();
        
            popup.add(refreshItem);
            popup.add(iPItem);
            popup.add(exitItem);
            
            trayIcon.setPopupMenu(popup);
            
            try {
            tray.add(trayIcon);
            } catch (AWTException e) {
            System.out.println("TrayIcon could not be added.");
            }
            
        try {
            getOrdersList(-1);
        } catch (Exception ex) {
            Logger.getLogger(GIT.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private void refreshUsersList(){
        try {
            String jsonResponse = getUsersList();
            JSONArray jsonArray = (JSONArray) new JSONTokener(jsonResponse).nextValue();
            for(int i=0; i<jsonArray.length(); i++){
                System.out.println(jsonArray.getJSONObject(i).getInt("id"));
                System.out.println(jsonArray.getJSONObject(i).getString("username"));
                int userId = jsonArray.getJSONObject(i).getInt("id");
                boolean notFound = true;
                for(User user : usersArray){
                    if(userId == user.getId()){
                        notFound = false;
                    }
                }
                if(notFound){
                    CheckboxMenuItem item = new CheckboxMenuItem(jsonArray.getJSONObject(i).getString("username"));
                    displayMenu.add(item);
                    User userTmp = new User(jsonArray.getJSONObject(i).getInt("id"), jsonArray.getJSONObject(i).getString("username"), item);
                    if(selectedUsers.contains(jsonArray.getJSONObject(i).getInt("id"))){
                        popup.insert(userTmp.getMenu(), 0);
                        item.setState(true);
                        refreshUser(userTmp);
                    }else{
                        userTmp.setState(false);
                    }
                    item.addItemListener(new ItemListener() {
                        @Override
                        public void itemStateChanged(ItemEvent e) {
                            for (User user : usersArray) {
                                if(user.getCheckboxMenuItem() == e.getSource()){
                                    if(((CheckboxMenuItem)e.getSource()).getState()){
                                        refreshUser(user);
                                        popup.insert(user.getMenu(), 0);
                                        selectedUsers.add(user.getId());
                                    }else{
                                        user.setState(false);
                                        selectedUsers.remove(new Integer(user.getId()));
                                        int itemsCount = popup.getItemCount();
                                        for(int i=0; i<itemsCount; i++){
                                            if(popup.getItem(i) == user.getMenu()){
                                                popup.remove(i);
                                                break;
                                            }
                                        }
                                    }
                                    break;
                                }
                            }
                            refreshConfiguration();
                        }
                    });
                    usersArray.add(userTmp);
                }
            }
            
        } catch (Exception ex) {
            Logger.getLogger(GIT.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void restoreConfiguratedUsers(){
        selectedUsers.clear();
        String line = null;

        try {
            // FileReader reads text files in the default encoding.
            FileReader fileReader = 
                new FileReader(fileName);

            // Always wrap FileReader in BufferedReader.
            BufferedReader bufferedReader = 
                new BufferedReader(fileReader);

            while((line = bufferedReader.readLine()) != null) {
                selectedUsers.add(new Integer(line));
                System.out.println(line);
            }   

            // Always close files.
            bufferedReader.close();         
        }
        catch(FileNotFoundException ex) {
            ex.printStackTrace();
            System.out.println(
                "Unable to open file '" + 
                fileName + "'");                
        }
        catch(IOException ex) {
            System.out.println(
                "Error reading file '" 
                + fileName + "'");                  
            // Or we could just do this: 
            // ex.printStackTrace();
        }
        
        for(User user : usersArray){
            boolean notFound = true;
            for(Integer userId : selectedUsers){
                if(userId == user.getId()){
                    notFound = false;
                }
            }
            
            if(notFound){
                user.setState(false);
                int itemsCount = popup.getItemCount();
                for(int i=0; i<itemsCount; i++){
                    if(popup.getItem(i) == user.getMenu()){
                        popup.remove(i);
                        break;
                    }
                }
            }else{
                if(!user.getState()){
                    refreshUser(user);
                    popup.insert(user.getMenu(), 0);
                }
            }
        }
    }
    
    public synchronized void refreshUser(User userToUpdate){
        try {
            String jsonResponse = getOrdersList(userToUpdate.getId());
            JSONArray jsonArray = (JSONArray) new JSONTokener(jsonResponse).nextValue();
            for(int i=0; i<jsonArray.length(); i++){
                System.out.println(jsonArray.getJSONObject(i).getInt("user_id"));
                System.out.println(jsonArray.getJSONObject(i).getJSONArray("orders_id"));
                for (User user : usersArray) {
                    if(user.getId() == jsonArray.getJSONObject(i).getInt("user_id")){
                        JSONArray jsonOrders = jsonArray.getJSONObject(i).getJSONArray("orders_id");
                        JSONArray jsonActions = jsonArray.getJSONObject(i).getJSONArray("actions");
                        int[] newOrders = new int[jsonOrders.length()];
                        int[] actions = new int[jsonActions.length()];
                        for(int z=0; z<newOrders.length; z++){
                            newOrders[z] = jsonOrders.getInt(z);
                            actions[z] = jsonActions.getInt(z);
                        }
                        user.refreshMenu(newOrders, actions);
                        user.setState(true);
                        break;
                    }
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(GIT.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public synchronized void refreshUsers(boolean forceRefresh){
        try {
            String jsonResponse = getOrdersList(-1);
            JSONArray jsonArray = (JSONArray) new JSONTokener(jsonResponse).nextValue();
            for(int i=0; i<jsonArray.length(); i++){
                System.out.println(jsonArray.getJSONObject(i).getInt("user_id"));
                System.out.println(jsonArray.getJSONObject(i).getJSONArray("orders_id"));
                for (User user : usersArray) {
                    if(user.getId() == jsonArray.getJSONObject(i).getInt("user_id")){
                        JSONArray jsonOrders = jsonArray.getJSONObject(i).getJSONArray("orders_id");
                        JSONArray jsonActions = jsonArray.getJSONObject(i).getJSONArray("actions");
                        int[] newOrders = new int[jsonOrders.length()];
                        int[] actions = new int[jsonActions.length()];
                        ArrayList<Order> oldOrders = user.getOrders();
                        ArrayList<Integer> ordersToPrint = new ArrayList<Integer>();
                        for(int z=0; z<newOrders.length; z++){
                            newOrders[z] = jsonOrders.getInt(z);
                            actions[z] = jsonActions.getInt(z);
                            boolean notFound = true;
                            for(Order order : oldOrders){
                                if(order.getId() == newOrders[z]){
                                    notFound = false;
                                }
                            }
                            if(notFound){
                                ordersToPrint.add(newOrders[z]);
                            }
                        }
                        if(forceRefresh){
                            user.refreshMenu(newOrders, actions);
                        }else{
                            if(ordersToPrint.size()>0){
                                user.refreshMenu(newOrders, actions);
                                for(int orderToPrint : ordersToPrint){
                                    for(Order order : user.getOrders()){
                                        if(order.getId() == orderToPrint){
                                            order.printOrder();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(GIT.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public synchronized void refreshDispayedUsers(boolean forceRefresh) throws Exception{
        String url = domain+"/orders/my-id";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("GET");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");


        BufferedReader in = new BufferedReader(
		        new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
        }
        in.close();
        
        //print result
        JSONObject jsonObject = (JSONObject) new JSONTokener(response.toString()).nextValue();
        int myId = jsonObject.getInt("id");
        if(myId > 0){
            boolean noOneSelected = true;
            for(User user : usersArray){
                if(user.getState()){
                    noOneSelected = false;
                    break;
                }
            }
            if(forceRefresh || noOneSelected){
                User selectedUser = null;
                for(User user: usersArray){
                    if(user.getId() == myId){
                        refreshUser(user);
                        selectedUser = user;
                        break;
                    }
                }

                if(selectedUser != null){
                    boolean notFound = true;
                    Iterator iterator = selectedUsers.iterator();
                    while(iterator.hasNext()){
                        int userId = (Integer)iterator.next();
                        if(myId != userId){
                            User userToDelete = null;
                            for (User user : usersArray) {
                                if(userId ==  user.getId()){
                                    user.setState(false);
                                    userToDelete = user;
                                    break;
                                }
                            }
                            iterator.remove();
                            int itemsCount = popup.getItemCount();
                            for(int i=0; i<itemsCount; i++){
                                if(popup.getItem(i) == userToDelete.getMenu()){
                                    popup.remove(i);
                                    break;
                                }
                            }
                        }else{
                            notFound = false;
                        }
                    }
                    if(notFound){
                        popup.insert(selectedUser.getMenu(), 0);
                        selectedUsers.add(new Integer(myId));
                    }
                }
            }
        }else{
            selectedUsers.clear();
            for(User user : usersArray){
                user.setState(false);
                int itemsCount = popup.getItemCount();
                for(int i=0; i<itemsCount; i++){
                    if(popup.getItem(i) == user.getMenu()){
                        popup.remove(i);
                        break;
                    }
                }
            }
        }
    }
    
    public void refreshIPBased(){

        try {
            // Assume default encoding.
            FileWriter fileWriter =
                new FileWriter(fileNameIP);

            // Always wrap FileWriter in BufferedWriter.
            BufferedWriter bufferedWriter =
                new BufferedWriter(fileWriter);

            // Note that write() does not automatically
            // append a newline character.
            if(this.iPBased){
                bufferedWriter.write("true");
            }else{
                bufferedWriter.write("false"); 
            }

            // Always close files.
            bufferedWriter.close();
        }
        catch(IOException ex) {
            System.out.println(
                "Error writing to file '"
                + fileNameIP + "'");
            // Or we could just do this:
            // ex.printStackTrace();
        }
    }
    
    public void refreshConfiguration(){
        System.out.println("Scrivo configurazione!!!");
        try {
            // Assume default encoding.
            FileWriter fileWriter =
                new FileWriter(fileName);

            // Always wrap FileWriter in BufferedWriter.
            BufferedWriter bufferedWriter =
                new BufferedWriter(fileWriter);

            // Note that write() does not automatically
            // append a newline character.
            for(int userId : selectedUsers){
                bufferedWriter.write(userId+"");
                bufferedWriter.newLine();
            }

            // Always close files.
            bufferedWriter.close();
        }
        catch(IOException ex) {
            System.out.println(
                "Error writing to file '"
                + fileName + "'");
            // Or we could just do this:
            // ex.printStackTrace();
        }
    }
    
    public static void main(String[] args){
        double value = 5.5;
        long first = (long) (5.5*10);
        long second = ((long) 5.5)*10;
        long third = (long)5.5*10;
        System.out.println("Ciao: "+first+" - "+second+" - "+third);
        
        new GIT();
    }
    
    private String getUsersList() throws Exception {

		//String url = "http://virtualbeach.homelinux.net/orders/users-list";
                //String url = "http://virtualbeach.gitgrado.it/orders/users-list";
                //String url = "http://test-virtualbeach.homelinux.net/orders/users-list";
                String url = domain+"/orders/users-list";
                
		URL obj = new URL(url);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();

		//add reuqest header
		con.setRequestMethod("POST");
		con.setRequestProperty("User-Agent", USER_AGENT);
		con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
                
                String urlParameters = "";

                // Send post request
                con.setDoOutput(true);
                DataOutputStream wr = new DataOutputStream(con.getOutputStream());
                wr.writeBytes(urlParameters);
                wr.flush();
                wr.close();

                int responseCode = con.getResponseCode();
                System.out.println("\nSending 'POST' request to URL : " + url);
                System.out.println("Post parameters : " + urlParameters);
                System.out.println("Response Code : " + responseCode);

                BufferedReader in = new BufferedReader(
                        new InputStreamReader(con.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                        response.append(inputLine);
                }
                in.close();

                //print result
                System.out.println("Ricevuto: "+response.toString());
                return response.toString();
	}
    
    private String getOrdersList(int userId) throws Exception {

		//String url = "http://virtualbeach.homelinux.net/orders/orders-list";
                //String url = "http://virtualbeach.gitgrado.it/orders/orders-list";
                //String url = "http://test-virtualbeach.homelinux.net/orders/orders-list";
                String url = domain+"/orders/orders-list";
		URL obj = new URL(url);
		HttpURLConnection con = (HttpURLConnection) obj.openConnection();

		//add reuqest header
		con.setRequestMethod("POST");
		con.setRequestProperty("User-Agent", USER_AGENT);
		con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
                
                
		
                String urlParameters = "";
                
                if(userId > 0){
                    urlParameters += "&ids[]="+userId;
                }else{
                    for (User user : usersArray) {
                        if(user.getState()){
                            urlParameters += "&ids[]="+user.getId();
                        }
                    }
                }
                if(urlParameters.length() > 0){
                    urlParameters = urlParameters.substring(1);
                    // Send post request
                    con.setDoOutput(true);
                    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
                    wr.writeBytes(urlParameters);
                    wr.flush();
                    wr.close();

                    int responseCode = con.getResponseCode();
                    System.out.println("\nSending 'POST' request to URL : " + url);
                    System.out.println("Post parameters : " + urlParameters);
                    System.out.println("Response Code : " + responseCode);

                    BufferedReader in = new BufferedReader(
                            new InputStreamReader(con.getInputStream()));
                    String inputLine;
                    StringBuffer response = new StringBuffer();

                    while ((inputLine = in.readLine()) != null) {
                            response.append(inputLine);
                    }
                    in.close();

                    //print result
                    System.out.println(response.toString());
                    return response.toString();
                }
            return "[]";
	}
    
    public void run() {
        boolean firstTime = true;
        boolean lastTimeNotIPBased = true;
        while(true){
            //System.out.println("Hello from a thread!");
            if(iPBased){
                try {
                    if(lastTimeNotIPBased){
                        refreshDispayedUsers(true);
                        lastTimeNotIPBased = false;
                    }else{
                        refreshDispayedUsers(false);
                    }
                } catch (Exception ex) {
                    Logger.getLogger(GIT.class.getName()).log(Level.SEVERE, null, ex);
                }
            }else{
                lastTimeNotIPBased = true;
            }
            try {
                if(firstTime){
                    refreshDispayedUsers(true);
                    refreshUsers(true);
                    firstTime = false;
                }else{
                    refreshDispayedUsers(false);
                    refreshUsers(false);
                }
            } catch (Exception ex) {
                Logger.getLogger(GIT.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                Thread.sleep(1000);                 //1000 milliseconds is one second.
            } catch(InterruptedException ex) {
                Thread.currentThread().interrupt();
            }
        }
    }
}