package controller

import (
	"image/color"
	"image/gif"
	"netease_control_center/interfaces/log"
	"netease_control_center/nembd/controller/is31fl3732a"
	"os"
	"time"
)

func GifShow() {
	log.Println(log.DebugLog, "Jump into gif show!!")
	fd, err := os.Open("/tmp/ihw.gif")

	if err == nil {
		gifs, err := gif.DecodeAll(fd)
		fd.Close()
		if err == nil {
			lc := gifs.LoopCount

			lcd := is31fl3732a.New(gifs.Config.Height, gifs.Config.Width)
			lcd.On()
			lcd.SetBtrightness(50)
			var buf [][]byte = make([][]byte, gifs.Config.Height)
			var buf2 [][]byte = make([][]byte, gifs.Config.Height)

			for i := 0; i < gifs.Config.Height; i++ {
				buf[i] = make([]byte, gifs.Config.Width)
				buf2[i] = make([]byte, gifs.Config.Width)
			}

			if lc == 0 {
				lc = 1
			}
			log.Println(log.DebugLog, "Begin go show, loop:", lc, gifs.Config, "Delay: ", gifs.Delay)

			for i := 0; i < lc; i++ {
				for k, v := range gifs.Image {
					for y := v.Rect.Min.Y; y < v.Rect.Max.Y; y++ {
						for x := v.Rect.Min.X; x < v.Rect.Max.X; x++ {
							ocolor := v.At(x, y)
							if gr, ok := color.GrayModel.Convert(ocolor).(color.Gray); ok {
								buf[y][x] = byte(gr.Y)
								if gr.Y > 0 {
									buf2[y][x] = byte(gr.Y)
								}
							}
						}
					}
					err = lcd.Show2(0, 0, gifs.Config.Width, gifs.Config.Height, &buf)
					//log.Println(log.DebugLog, "Show buf", buf, err)
					time.Sleep(time.Duration(gifs.Delay[k]) * 10 * time.Millisecond)
				}
			}
			err = lcd.Show2(0, 0, gifs.Config.Width, gifs.Config.Height, &buf2)
		} else {
			log.Println(log.ErrorLog, "gif decode error ", err)
		}
	} else {
		log.Println(log.ErrorLog, "Open file error", err)
	}

	log.Println(log.DebugLog, "Show end")
}
