package handlers

import (
	"currenstore/config"
	"currenstore/database"
	"currenstore/models"
	"encoding/xml"
	"fmt"
	"io"
	"net/http"
	"net/url"
	"os"
	"time"

	_ "github.com/mattn/go-sqlite3"
	log "github.com/sirupsen/logrus"
	"golang.org/x/text/encoding/charmap"
)

func InsertTest() {
	db := database.DBConn
	t := time.Now()
	sql_additem := `
	INSERT OR REPLACE INTO history_data(
		currency_id,
		curs_date,
		num_code,
		char_code,
		nominal,
		currency_name,
		currency_value
	) values('ABC', ?, '92', 'EUR', '1', 'EUR', '24,1')
	`

	stmt, err := db.Prepare(sql_additem)
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}
	defer stmt.Close()

	_, err2 := stmt.Exec(t)
	if err2 != nil {
		log.Fatal(err2)
		os.Exit(1)
	}
}

func GetCurrencyByDate(fromDate string) models.ValCurs {
	log.Printf("GetCurrencyByDate for: %s", fromDate)
	var cursByDate models.ValCurs
	querydate := queryCBRFDateFormat(fromDate)

	params := "date_req=" + url.QueryEscape(querydate)
	path := fmt.Sprintf("https://cbr.ru/scripts/XML_daily.asp?%s", params)

	resp, err := http.Get(path)

	if err != nil {
		log.Errorf("CBR Query error: %s", err)
	}

	defer resp.Body.Close()

	if resp.StatusCode == 200 {
		log.Printf("Received response 200 from CBR")
		d := xml.NewDecoder(resp.Body)
		d.CharsetReader = func(charset string, input io.Reader) (io.Reader, error) {
			switch charset {
			case "windows-1251":
				return charmap.Windows1251.NewDecoder().Reader(input), nil
			default:
				return nil, fmt.Errorf("unknown charset: %s", charset)
			}
		}

		err = d.Decode(&cursByDate)
		if err != nil {
			log.Errorf("Decode error: %s", err)
		}
	}
	return cursByDate
}

func GetAndSaveByDate(fromDate string) {

	var targetLayout string = "02.01.2006"

	checkDateTime, err := time.Parse("2006-01-02", fromDate)
	if err != nil {
		log.Errorf("TimeDate parsing error: %s", err)
	}

	queryDate := checkDateTime.Format(targetLayout)

	currencyModel := GetCurrencyByDate(queryDate)
	database.SaveExchangeRateToDB(currencyModel, fromDate)
}

func GetAndSaveForToday() {
	todayDate := time.Now()
	var targetLayout string = "02.01.2006"
	queryDate := todayDate.Format(targetLayout)
	log.Printf("Save exchange for today: %s", queryDate)
	currencyModel := GetCurrencyByDate(queryDate)
	database.SaveExchangeRateToDB(currencyModel, "")
}

func GetAndSaveForExtDate() {
	gd := config.GetGlobalDate()

	//Get and save currency data
	log.Printf("Save exchange for extdate: %s", gd)
	currencyModel := GetCurrencyByDate(gd)
	database.SaveExchangeRateToDB(currencyModel, "")

	//Increment GlobalDate
	layout := "02.01.2006"
	t, err := time.Parse(layout, gd)

	if err != nil {
		log.Println(err)
	}
	gdPlusDayTime := t.AddDate(0, 0, 1)
	config.SetGlobalDate(gdPlusDayTime.Format(layout))
}

func queryCBRFDateFormat(fromDate string) string {
	var timeFormat string = "02/01/2006"
	var fromDateLayout string = "02.01.2006"
	if fromDate == "" {
		t := time.Now()
		return t.Format(timeFormat)
	}
	t, _ := time.Parse(fromDateLayout, fromDate)
	return t.Format(timeFormat)
}
