package main

import (
	"fmt"
	"log"
	"os"
	"path"
	"strconv"
	"strings"
	"time"
)

var DashboardDir = "DASHBOARD"

type NextDashboardFile struct {
	Id     int64     `json:"id"`
	Name   string    `json:"name"`
	Screen int       `json:"screen"`
	Date   time.Time `json:"date"`
}

func (ndf *NextDashboardFile) GetId() int64 {
	return ndf.Id
}

func (ndf *NextDashboardFile) GetDate() *time.Time {
	return &ndf.Date
}

// NewDashboardDistList creates a distList from the given src directory
func NewDashboardDistList(src string) (*distList, error) {
	var list []DistEvent

	files, err := os.ReadDir(DashboardDir)
	if err != nil {
		return nil, err
	}

	for _, file := range files {
		if !strings.HasPrefix(file.Name(), "public") || len(file.Name()) < 18 {
			continue
		}

		ts, err := strconv.ParseInt(file.Name()[8:18], 10, 64)
		if err == nil {
			s, _ := strconv.Atoi(file.Name()[6:7])
			list = append(list, &NextDashboardFile{
				Id:     ts * int64(s),
				Name:   file.Name(),
				Screen: s,
				Date:   time.Unix(ts, 0),
			})
		}
	}

	return &distList{List: list, Timer: time.NewTimer(time.Minute)}, nil
}

func parseDashboardFilename(fname string) (int64, error) {
	return strconv.ParseInt(fname[8:18], 10, 64)
}

func newDashboardFile(l *distList, raw_path string) {
	bpath := path.Base(raw_path)

	if !strings.HasPrefix(bpath, "public") || len(bpath) < 18 {
		return
	}

	if ts, err := parseSettingsFilename(bpath); err == nil {
		activateTime := time.Unix(ts, 0)

		log.Printf("Preparing %s: activation time at %s", bpath, activateTime)

		s, _ := strconv.Atoi(bpath[6:7])
		l.AddEvent(&NextDashboardFile{
			Id:     ts * int64(s),
			Name:   bpath,
			Screen: s,
			Date:   activateTime,
		}, nil)
	} else {
		log.Println("WARNING: Unknown file to treat: not a valid timestamp:", err.Error())
	}
}

func treatDashboardFile(e *NextDashboardFile) {
	err := os.Rename(path.Join(DashboardDir, e.Name), path.Join(DashboardDir, fmt.Sprintf("public%d.json", e.Screen)))
	if err != nil {
		log.Printf("Unable to move %q: %s", e.Name, err.Error())
	}
}
