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

package fetcherv1

import (
	"net/http"

	"github.com/PuerkitoBio/goquery"
	"github.com/rs/zerolog"
	"gitlab.com/pztrn/flagger"

	"gitlab.com/fat0troll/uploader_tools/internal/context"
)

var (
	c               *context.Context
	dclient         http.Client
	dlog            zerolog.Logger
	forumPages      map[int]*goquery.Document
	forumPagesLinks map[string]string
	uberDebug       bool
)

// New initializes package
func New(cc *context.Context) {
	c = cc
	dlog = c.Logger.With().Str("модуль", "fetcher").Int("версия", 1).Logger()

	_ = c.Flagger.AddFlag(&flagger.Flag{
		Name:         "forum",
		Description:  "Номер форума, торренты с которого нужно скачать",
		Type:         "int",
		DefaultValue: 0,
	})

	_ = c.Flagger.AddFlag(&flagger.Flag{
		Name:         "fetcherDebug",
		Description:  "Запустить модуль fetcher в дебаг-режиме",
		Type:         "bool",
		DefaultValue: false,
	})

	forumPages = make(map[int]*goquery.Document)
	forumPagesLinks = make(map[string]string)

	dlog.Info().Msg("Модуль инициализирован")
}

// Process handles authorization
func Process() {
	uberDebug, _ = c.Flagger.GetBoolValue("fetcherDebug")
	forumID, _ := c.Flagger.GetIntValue("forum")
	if forumID == 0 {
		dlog.Fatal().Msg("Номер форума не указан. Используйте ключ -forum XXX, чтобы указать номер форума")
	}

	dlog.Info().Int("forum ID", forumID).Msg("Получен ID форума, начинаем работу...")

	fetch(forumID)
}