package events_alerter

import (
	"database/sql"
	"fmt"
	"strings"
	"time"
)
import _ "github.com/go-sql-driver/mysql"

type MsgStr struct {
	remote  string
	message string
}

func (msg MsgStr) Remote() string {
	return msg.remote
}

func (msg MsgStr) Message() string {
	return msg.message
}

type MsgInt interface {
	Remote() string
	Message() string
}

type DbRequester struct {
	login    string
	pass     string
	host     string
	database string
}

func (dbStruct *DbRequester) ReqPrepare(sqlStr ...string) string {
	if len(sqlStr) > 1 {
		values := make([]interface{}, len(sqlStr)-1)
		for i, _ := range sqlStr[1:] {
			k := i + 1
			values[i] = sqlStr[k]
		}
		return fmt.Sprintf(sqlStr[0], values...)
	} else {
		return sqlStr[0]
	}

}

func (dbStruct *DbRequester) Requester(sqlStr string) (allResult [][]string, err error) {
	connStr := fmt.Sprintf("%v:%v@tcp(%v)/%v", dbStruct.login, dbStruct.pass, dbStruct.host, dbStruct.database)
	db, err := sql.Open("mysql", connStr)
	if err != nil {
		return
	}
	defer db.Close()
	err = db.Ping()
	if err != nil {
		return
	}
	req, err := db.Prepare(sqlStr)
	if err != nil {
		return
	}
	defer req.Close()
	rows, err := req.Query() //пыщим запросий
	if err != nil {
		return
	}
	cols, err := rows.Columns() // получаем слайс стрингов с названиями колонок
	if err != nil {
		return
	}
	rawResult := make([][]byte, len(cols)) // слайс слайсов байт, это одна строка выхлопа сырая

	dest := make([]interface{}, len(cols)) // слайс пустых интерфейсов
	for i, _ := range rawResult {
		dest[i] = &rawResult[i] // Put pointers to each string in the interface slice
	}
	for rows.Next() {
		err = rows.Scan(dest...)
		if err != nil {
			return
		}
		result := make([]string, len(cols)) // слайс строк, одна строка выхлопа, которую надо добавить в общий выхлоп
		for i, raw := range rawResult {
			if raw == nil {
				result[i] = "Null"
			} else {
				result[i] = string(raw)
			}
		}
		allResult = append(allResult, result)
	}
	return
}

func BuildAlert() (msgSl []MsgInt) {
	msgTpl := `Вспомни! %v время для важного!
Задача '%v' ждет тебя, 
Лови ссыль:
https://pm.constanta-smt.ru/index.php/tasksComments?tasks_id=%v&projects_id=%v`
	dbuser := DbRequester{
		login:    "bot",
		pass:     "z68puEFJhEBtS",
		host:     "10.176.120.51",
		database: "qdpm",
	}
	createdFormat := "2006-01-02 15:04"
	t := time.Now()
	sqlTpl := `select extra_fields_list.value, tasks.projects_id as pid, tasks.id as tid, name tname, tasks.assigned_to as users
	from extra_fields_list, tasks
	where extra_fields_list.extra_fields_id = 10 and extra_fields_list.value = '%v' and extra_fields_list.bind_id = tasks.id ;`
	//sqlTpl := `select extra_fields_list.value, tasks.projects_id as pid, tasks.id as tid, name tname, tasks.assigned_to as users
	//from extra_fields_list, tasks
	//where extra_fields_list.extra_fields_id = 10 and extra_fields_list.value <> '' and extra_fields_list.bind_id = tasks.id ;`
	fmt.Println(dbuser.ReqPrepare(sqlTpl, t.Format(createdFormat)))
	res, err := dbuser.Requester(dbuser.ReqPrepare(sqlTpl, t.Format(createdFormat)))
	fmt.Printf("%#v, %#v\n", res, err)

	if len(res) > 0 { // обработка запроса, если найдено больше 0 строк
		for _, v := range res {
			fmt.Println(v)
			msgStr := fmt.Sprintf(msgTpl, v[0], v[3], v[2], v[1])
			uidSl := strings.Split(v[4], ",")
			jidSl := make([]string, len(uidSl))
			for _, uid := range uidSl {
				sqlTpl = "select value from qdpm.extra_fields_list where extra_fields_id = 11 and bind_id = '%v';"
				jid, _ := dbuser.Requester(dbuser.ReqPrepare(sqlTpl, uid))
				if len(jid) > 0 {
					tmpJid := jid[0][0]
					jidSl = append(jidSl, tmpJid)
					fmt.Printf("%v\n", tmpJid)
					tmpMsg := MsgStr{remote: tmpJid, message: msgStr}
					msgSl = append(msgSl, tmpMsg)
				}
			}
		}
		fmt.Println(msgSl)
	}
	return
}
