// NNM-Club torrent filess mass downloader
// Created for Uploaders group
// Copyright (c) 2012-2019 Vladimir "fat0troll" Hodakov

package loginerv1

import (
	"bufio"
	"net/http"
	"net/url"
	"os"
	"strings"
	"time"
)

// login function name is self-descriptive.
// After successful login it will write cookie file and config in system's
// config directory
func login() {
	dlog.Info().Msg("Введите адрес сайта NNM-Club, без протокола (к примеру, nnmclub.ro)")
	// First enter is site name, second and third are user credentials
	scanner := bufio.NewScanner(os.Stdin)
	scanline := 0
	for scanner.Scan() {
		scanline++
		switch {
		case scanline == 1:
			c.Config.URL = scanner.Text()
			dlog.Info().Msg("Введите имя пользователя")
		case scanline == 2:
			c.Config.Username = scanner.Text()
			dlog.Info().Msg("Введите пароль")
		default:
			c.Config.Password = scanner.Text()
		}
		if scanline == 3 {
			break
		}
	}
	if scanner.Err() != nil {
		dlog.Fatal().Err(scanner.Err()).Msg("Не удалось прочитать пользовательский ввод.")
	}

	c.SaveConfig()

	obtainCookies()

	dlog.Info().Msg("Логин прошёл успешно. Перезапустите программу с ключём -forum НОМЕР_ФОРУМА.")
	os.Exit(0)
}

// obtainCookie tries to login to NNM-Club and saves resulting cookie
// If it can't save cookie, the program will terminate with error and you will
// need to authorize again or retry cookie obtaining.
func obtainCookies() {
	// This value is obtained from login.php sources.
	nnmClubCode := "58161005a04f0ee5"

	client := http.Client{
		// This is disables redirects for this request. Otherwise we can't obtain cookies
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse
		},
	}

	formData := url.Values{}
	formData.Add("username", c.Config.Username)
	formData.Add("password", c.Config.Password)
	formData.Add("autologin", "on")
	formData.Add("redirect", "index.php")
	formData.Add("code", nnmClubCode)
	formData.Add("login", "%C2%F5%EE%E4")

	url := "https://" + c.Config.URL + "/forum/login.php"
	req, _ := http.NewRequest(http.MethodPost, url, strings.NewReader(formData.Encode()))
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded; charset=utf-8")

	retryCount := 0
	var resp *http.Response
	var err error
	for {
		if retryCount == 10 {
			dlog.Fatal().Err(err).Msg("Не удалось отправить запрос на авторизацию в NNM-Club.")
		}
		resp, err = client.Do(req)
		if err != nil {
			dlog.Debug().Err(err).Int("попытка", retryCount).Msg("Не удалось отправить запрос, попробуем ещё раз")
			retryCount++
			time.Sleep(2 * time.Second)
		} else {
			break
		}
	}
	defer resp.Body.Close()

	if len(resp.Cookies()) == 0 {
		dlog.Fatal().Msg("Не удалось получить печеньки от сайта NNM-Club. Неправильные имя/пароль или адрес сайта.")
	}

	c.SetCookies(resp.Cookies())

	dlog.Info().Str("username", c.Config.Username).Msg("Успешный логин.")
}