/*
 * Juick
 * Copyright (C) 2008-2013, Ugnich Anton
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.juick.www;

import com.juick.server.UserQueries;
import com.mitchellbosecke.pebble.error.PebbleException;
import com.mitchellbosecke.pebble.template.PebbleTemplate;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Ugnich Anton
 */
public class SignUp {

    protected void doGet(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, PebbleException {
        com.juick.User visitor = Utils.getVisitorUser(sql, request, response);

        String type = request.getParameter("type");
        String hash = request.getParameter("hash");
        if (type == null || type.isEmpty() || hash == null || hash.isEmpty() || hash.length() > 36 || !type.matches("^[a-zA-Z0-9\\-]+$") || !hash.matches("^[a-zA-Z0-9\\-]+$")) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        String account = null;
        switch (type) {
            case "fb":
                account = getFacebookNameByHash(sql, hash);
                break;
            case "vk":
                account = getVKNameByHash(sql, hash);
                break;
            case "xmpp":
                account = getJIDByHash(sql, hash);
                break;
            case "durov":
                account = getTelegramNameByHash(sql, hash);
                break;
        }
        if (account == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        response.setContentType("text/html; charset=UTF-8");
        try (PrintWriter out = response.getWriter()) {
            PebbleTemplate template = Utils.getEngine().getTemplate("views/signup.html");
            Map<String, Object> context = new HashMap<>();
            context.put("title", "Новый пользователь");
            context.put("visitor", visitor);
            context.put("account", account);
            context.put("type", type);
            context.put("hash", hash);
            template.evaluate(out, context);
        }
    }

    protected void doPost(JdbcTemplate sql, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        com.juick.User visitor = Utils.getVisitorUser(sql, request, response);
        int uid = 0;

        String type = request.getParameter("type");
        String hash = request.getParameter("hash");
        if (type == null || type.isEmpty() || hash == null || hash.isEmpty() || hash.length() > 36 || !type.matches("^[a-zA-Z0-9\\-]+$") || !hash.matches("^[a-zA-Z0-9\\-]+$")) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }

        String action = request.getParameter("action");
        if (action.charAt(0) == 'l') {

            if (visitor.getUid() == 0) {
                String username = request.getParameter("username");
                String password = request.getParameter("password");
                if (username == null || password == null || username.length() > 32 || password.isEmpty()) {
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST);
                    return;
                }
                uid = com.juick.server.UserQueries.checkPassword(sql, username, password);
            } else {
                uid = visitor.getUid();
            }

            if (uid <= 0) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }

            if (!(type.charAt(0) == 'f' && setFacebookUser(sql, hash, uid))
                    && !(type.charAt(0) == 'v' && setVKUser(sql, hash, uid))
                    && !(type.charAt(0) == 'd' && setTelegramUser(sql, hash, uid))
                    && !(type.charAt(0) == 'x' && setJIDUser(sql, hash, uid))) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return;
            }

        } else { // Create new account
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            if (username == null || password == null || username.length() < 2 || username.length() > 16 || !username.matches("^[a-zA-Z0-9\\-]+$") || password.length() < 6 || password.length() > 32) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }

            // CHECK USERNAME

            uid = UserQueries.createUser(sql, username, password);
            if (uid <= 0) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return;
            }

            if (!(type.charAt(0) == 'f' && setFacebookUser(sql, hash, uid))
                    && !(type.charAt(0) == 'v' && setVKUser(sql, hash, uid))
                    && !(type.charAt(0) == 'd' && setTelegramUser(sql, hash, uid))
                    && !(type.charAt(0) == 'x' && setJIDUser(sql, hash, uid))) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return;
            }

            int ref = 0;
            String sRef = Utils.getCookie(request, "ref");
            if (sRef != null) {
                try {
                    ref = Integer.parseInt(sRef);
                } catch (Exception e) {
                }
            }

            if (ref > 0) {
                setUserRef(sql, uid, ref);
            }

            visitor = null;
        }

        if (visitor == null) {
            hash = com.juick.server.UserQueries.getHashByUID(sql, uid);
            Cookie c = new Cookie("hash", hash);
            c.setMaxAge(365 * 24 * 60 * 60);
            response.addCookie(c);
        }

        response.sendRedirect("/");
    }

    private boolean setUserRef(JdbcTemplate sql, int uid, int ref) {
        return sql.update("INSERT INTO users_refs(user_id,ref) VALUES (?,?)", uid, ref) > 0;
    }

    private String getFacebookNameByHash(JdbcTemplate sql, String hash) {
        try {
            List<Pair<String, String>> fb = sql.query("SELECT fb_name,fb_link FROM facebook WHERE loginhash=?",
                    (rs, num) -> Pair.of(rs.getString(1), rs.getString(2)), hash);
            if (fb.size() > 0) {
                return "<a href=\"" + fb.get(0).getRight() + "\" rel=\"nofollow\">" + fb.get(0).getLeft() + "</a>";
            }
            return null;
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }
    private String getTelegramNameByHash(JdbcTemplate sql, String hash) {
        try {
            String name = sql.queryForObject("SELECT tg_name FROM telegram WHERE loginhash=?", String.class, hash);
            return "<a href=\"https://telegram.me/" + name + "\" rel=\"nofollow\">" + name + "</a>";
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    private boolean setFacebookUser(JdbcTemplate sql, String hash, int uid) {
        return sql.update("UPDATE facebook SET user_id=?,loginhash=NULL WHERE loginhash=?", uid, hash) > 0;
    }

    private String getVKNameByHash(JdbcTemplate sql, String hash) {
        List<Pair<String, String>> logins = sql.query("SELECT vk_name,vk_link FROM vk WHERE loginhash=?",
                (rs, num) -> Pair.of(rs.getString(1), rs.getString(2)), hash);
        if (logins.size() > 0) {
            return "<a href=\"http://vk.com/" + logins.get(0).getRight() + "\" rel=\"nofollow\">" + logins.get(0).getLeft() + "</a>";
        }
        return null;
    }

    private boolean setVKUser(JdbcTemplate sql, String hash, int uid) {
        return sql.update("UPDATE vk SET user_id=?,loginhash=NULL WHERE loginhash=?", uid, hash) > 0;
    }
    private boolean setTelegramUser(JdbcTemplate sql, String hash, int uid) {
        return sql.update("UPDATE telegram SET user_id=?,loginhash=NULL WHERE loginhash=?", uid, hash) > 0;
    }

    private String getJIDByHash(JdbcTemplate sql, String hash) {
        try {
            return sql.queryForObject("SELECT jid FROM jids WHERE loginhash=?", String.class, hash);
        } catch (EmptyResultDataAccessException e) {
            return null;
        }
    }

    private boolean setJIDUser(JdbcTemplate sql, String hash, int uid) {
        return sql.update("UPDATE jids SET user_id=?,loginhash=NULL WHERE loginhash=?", uid, hash) > 0;
    }
}