package internal

import (
	"context"
	"fmt"
	"path/filepath"

	"github.com/gotd/td/telegram/downloader"
	"github.com/gotd/td/tg"
	"github.com/pkg/errors"
	"github.com/samber/lo"
)

func (t *TClient) Channel(ctx context.Context, channel *tg.Channel, offset int) error {
	inputPeer := &tg.InputPeerChannel{ChannelID: channel.ID, AccessHash: channel.AccessHash}
	messages, err := t.api.MessagesGetHistory(ctx, &tg.MessagesGetHistoryRequest{
		Peer:     inputPeer,
		Limit:    10,
		OffsetID: offset,
	})
	if err != nil {
		return errors.Wrap(err, "messages.getHistory")
	}

	downloader := downloader.NewDownloader()
	lo.ForEach(messages.(*tg.MessagesChannelMessages).GetMessages(), func(item tg.MessageClass, index int) {
		msg, ok := item.(*tg.Message)
		if !ok {
			fmt.Println("ID: get failed")
			return
		}

		if !t.downloadMedia {
			return
		}

		if mediaClass, ok := msg.GetMedia(); ok {
			if photoClass, ok := mediaClass.(*tg.MessageMediaPhoto).GetPhoto(); ok {
				photo := photoClass.(*tg.Photo)

				thumbSize := ""
				if len(photo.Sizes) > 1 {
					thumbSize = photo.Sizes[len(photo.Sizes)-1].GetType()
				}

				location := &tg.InputPhotoFileLocation{
					ID:            photo.GetID(),
					AccessHash:    photo.GetAccessHash(),
					FileReference: photo.GetFileReference(),
					ThumbSize:     thumbSize,
				}

				saveTo := lo.Must(filepath.Abs(fmt.Sprintf("./photos/%d.jpg", photo.GetID())))
				storage, err := downloader.Download(t.api, location).ToPath(ctx, saveTo)

				if err != nil {
					fmt.Println(err)
				} else {
					fmt.Println("Downloaded : ", storage)
				}
			}
		}
	})

	return nil
}
