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

import com.google.common.base.Objects;
import com.google.gson.Gson;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import tool.SqlTool;

/**
 *
 * @author martin
 */
public class Contact extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, 
                         HttpServletResponse response)
                         throws ServletException, IOException {
        String path = request.getPathInfo();
        if (path.matches("^/$")){
            String sql = "SELECT contact_name AS name, "
                              + "contact_address AS address, "
                              + "contact_phone AS phone, "
                              + "contact_mobile AS mobile, "
                              + "contact_city AS city, "
                              + "contact_zip AS zip "
                              + "FROM contact LIMIT 25";
            try {
                Connection connection = SqlTool.getConnection("jdbc:mysql://orford/contact", "root", "root");
                List<Map<String,Object>> result = SqlTool.query(connection, sql);
                String json = new Gson().toJson(result,List.class);
                response.setContentType("application/json");
                response.getWriter().write(json);
            } catch (ClassNotFoundException ex) {
                response.getWriter().write(ex.getMessage()+"fxgsd");
                Logger.getLogger(Contact.class.getName()).log(Level.SEVERE, null, ex);
            } catch (SQLException ex) {
                response.getWriter().write(ex.getMessage());
            }
        }
        else if (path.matches("^/search")){
            response.getWriter().write("B==D");
        }
        else{
            
            response.getWriter().write(path);
            //response.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, 
                          HttpServletResponse response)
                          throws ServletException, IOException {
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }

}
