package main

import (
	"errors"
	"fmt"
	"io"
	"os"
	"path/filepath"
	"time"

	"git.milar.in/nyaanime/logic"
	"git.milar.in/nyaanime/model"
	"git.milar.in/nyaanime/parsers"
	"github.com/fatih/color"
)

func HandleFile(path string) <-chan byte {
	out := make(chan byte, 1024)
	defer close(out)
	w := NewWriterFromByteChan(out)

	fmt.Fprint(w, color.MagentaString("%s file found: %s\n", time.Now().Format("2006-01-02 15:04:05"), path))

	for _, parser := range parsers.Parsers {
		parsedFile, ok := parser.FileParser(&parser, path)
		if !ok {
			fmt.Fprint(w, color.YellowString("\tnot parsable with parser '%s'\n", parser.Identity))
			continue
		}

		fmt.Fprint(w, color.GreenString("\tparsable with parser '%s'\n", parser.Identity))

		anime, err := logic.SearchAnimeByTitle(parsedFile.OriginalAnimeTitle)
		if err != nil {
			fmt.Fprint(w, color.RedString("\tanime not found: '%s'\n", parsedFile.OriginalAnimeTitle))
			continue
		}

		parsedFile.Anime = anime
		HandleParsedFile(w, parsedFile)
		break
	}

	return out
}

func HandleParsedFile(w io.Writer, parsedFile *model.ParsedFile) {
	newFilePrio := logic.NewFilePriority(parsedFile)
	oldFilePrio, animeEpNotExistLocally := logic.GetAnimeEpProps(parsedFile.AnimeEpisode())

	// debug output
	if animeEpNotExistLocally {
		fmt.Fprint(w, color.YellowString("\tfile exists locally\n"))
		fmt.Fprint(w, color.YellowString("\t    local file: %s\n", FilePrio2Str(oldFilePrio)))
		fmt.Fprint(w, color.YellowString("\t    new file:   %s\n", FilePrio2Str(newFilePrio)))
		if newFilePrio.Priority > oldFilePrio.Priority {
			fmt.Fprint(w, color.GreenString("\t    overwrite local file\n"))
		} else {
			fmt.Fprint(w, color.YellowString("\t    ignore new file\n"))
		}
	}

	// delete files with lower priority from DownloadPath
	if DeleteLowPriorityFiles && animeEpNotExistLocally && oldFilePrio.Priority >= newFilePrio.Priority {
		fmt.Fprint(w, color.YellowString("\tdelete file with lower priority '%s'", parsedFile.File))
		err := os.Remove(parsedFile.File)
		if err != nil {
			fmt.Fprint(w, color.RedString(" failed: '%s'\n", err.Error()))
		} else {
			fmt.Fprint(w, color.GreenString(" done\n"))
		}
		return
	}

	if !animeEpNotExistLocally || newFilePrio.Priority > oldFilePrio.Priority {
		// TODO remove old file when overwriting existing episode (might have other file extension)
		if err := OrganizeAnimeEpisode(w, parsedFile); err != nil {
			fmt.Fprint(w, color.RedString("\terror: %s\n", err.Error()))
		}
	}
}

func OrganizeAnimeEpisode(w io.Writer, parsedFile *model.ParsedFile) error {
	start := time.Now()

	oldFile := filepath.Join(DownloadPath, parsedFile.File)
	newFile := logic.GetAnimeEpFilepath(parsedFile.AnimeEpisode(), filepath.Ext(parsedFile.File))
	lockFile := logic.GetAnimeEpFilepath(parsedFile.AnimeEpisode(), "lock")

	fmt.Fprint(w, color.BlueString("\tmove file\n\t    from: '%s'\n\t    to: '%s'\n", oldFile, newFile))

	if err := os.MkdirAll(filepath.Dir(newFile), os.ModePerm); err != nil {
		return err
	}

	if err := os.Chown(filepath.Dir(newFile), Uid, Gid); err != nil {
		return err
	}

	if _, err := os.Stat(newFile); err != nil && !errors.Is(err, os.ErrNotExist) {
		return err
	}

	inputFile, err := os.Open(oldFile)
	if err != nil {
		return err
	}
	defer inputFile.Close()

	outputFile, err := os.Create(newFile)
	if err != nil {
		return err
	}
	defer outputFile.Close()

	if err := os.Chown(newFile, Uid, Gid); err != nil {
		return err
	}

	written, err := io.Copy(outputFile, inputFile)
	if err != nil {
		return err
	}

	if err = os.Remove(oldFile); err != nil {
		return err
	}

	if err = os.Remove(lockFile); err != nil && !errors.Is(err, os.ErrNotExist) {
		return err
	}

	fmt.Fprint(w, color.BlueString("\t    done (copied %s in %s)\n", FormatBytes(written), time.Since(start).Truncate(100*time.Millisecond)))

	return nil
}
