package clock

import (
	"image"
	"image/color"
	"image/png"
	"strconv"
	"io"
	"time"

	"git.niplace.ru/XoxJlopeZ_1488/clock/imageutils"
	"git.niplace.ru/XoxJlopeZ_1488/clock/letter"
)

func Check(err error) {
	if err != nil {
		panic(err)
	}
}

var img1, img2 = letter.Nums[6].Render(), letter.Nums[9].Render()

func DownRightBlank(img image.Image) image.Image {
	clr := color.White
	img = letter.Blank(img, clr, imageutils.Down)
	return letter.Blank(img, clr, imageutils.Right)
}

func LeftUpBlank(img image.Image) image.Image {
	clr := color.White
	img = letter.Blank(img, clr, imageutils.Left)
	return letter.Blank(img, clr, imageutils.Up)
}

func RenderNum(n int) image.Image {
	var img image.Image = image.NewRGBA(image.Rect(0,0,0,0))
	s := strconv.Itoa(n)
	for i := range s {
		n, err := strconv.Atoi(string(s[i]))
		if err != nil {
			panic(err)
		}
		println(n)

		num := letter.Nums[n].Render()
		num = DownRightBlank(num)
		img = imageutils.Concat(img, num, imageutils.Right)
	}
	img = LeftUpBlank(img)
	return img
}

func RenderTime(t time.Time) image.Image {
	hour := RenderNum(t.Hour())
	if t.Hour() < 10 {
		hour = imageutils.Concat(
			DownRightBlank(letter.Empty), hour, imageutils.Right)
	}
	minute := RenderNum(t.Minute())
	if t.Minute() < 10 {
		minute = imageutils.Concat(
			DownRightBlank(letter.Empty), minute, imageutils.Right)
	}

	img := imageutils.Concat(hour, minute, imageutils.Down)
	return img
}

func Margin(img image.Image, length int) image.Image {
	for i := 0; i < length; i++ {
		img = LeftUpBlank(DownRightBlank(img))
	}
	return img
}

func Time(w io.Writer) {
	t := time.Now()
	img := RenderTime(t)
	img = Margin(img, 3)
	img = imageutils.Scale(img, 1<<6)
	Check(png.Encode(w, img))

}
