package main

import (
	"context"
	"flag"
	"fmt"
	"io"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"typorainstaller/common"
	"typorainstaller/constants"
)

func pull(pull_type int) error {
	var urlToDownload string
	var fname string
	switch pull_type {
	case PULL_INSTALLER:
		urlToDownload = "https://git.godopu.net/Godopu/typora-installer/media/branch/main/installer/" + constants.Installer
		fname = constants.Installer
	case PULL_CONFIG:
		urlToDownload = "https://git.godopu.net/Godopu/typora-installer/media/branch/main/themes.zip"
		fname = "themes.zip"
	}

	resp, err := http.Get(urlToDownload)
	if err != nil {
		return err
	}

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

	_, err = io.Copy(file, resp.Body)
	if err != nil {
		return err
	}

	return nil
}

func installOnWindows(ctx context.Context) (context.Context, error) {
	cmd := exec.Command("powershell", "-nologo", "-noprofile")
	stdin, err := cmd.StdinPipe()
	if err != nil {
		return nil, err
	}

	errorCh := make(chan error, 1)
	defer close(errorCh)

	go func() {
		defer stdin.Close()
		fmt.Fprintln(stdin, "$T = Get-Date")
		fmt.Fprintln(stdin, "Set-Date -Date ($T).AddYears(30)")
		bout, err := exec.Command(constants.Installer).Output()
		if err != nil {
			errorCh <- err
		}
		fmt.Println(bout)
		fmt.Fprintln(stdin, "Set-Date -Date ($T)")
		errorCh <- nil
	}()

	_, err = cmd.Output()
	if err != nil {
		errorCh <- err
	}

	return nil, <-errorCh
}

func configOnWindows() error {
	err := os.RemoveAll(filepath.Join(constants.ConfigPath, "themes"))
	if err != nil {
		return err
	}
	return common.Unzip("./themes.zip", constants.ConfigPath)
}

const (
	PULL_INSTALLER = iota
	PULL_CONFIG
)

func IsExistConfig() bool {
	if _, err := os.Stat("./themes.zip"); err == nil {
		return true
	}

	return false
}
func IsExistInstaller() bool {
	// if _, err := os.Stat("./themes.zip"); err == nil {
	// 	return true
	// }

	return false
}

func main() {

	conf := flag.Bool("config", false, "Config")
	inst := flag.Bool("install", false, "Install")
	clear := flag.Bool("clear", false, "Clear cache")
	flag.Parse()

	if *clear {
		err := os.RemoveAll(constants.WorkPath)
		if err != nil {
			panic(err)
		}
	}

	err := os.MkdirAll(constants.WorkPath, os.ModePerm)
	if err != nil {
		panic(err)
	}

	err = os.Chdir(constants.WorkPath)
	if err != nil {
		panic(err)
	}

	if *conf {
		if !IsExistConfig() {
			fmt.Println("Downloading config file...")
			pull(PULL_CONFIG)
			fmt.Println("Download Success")
		}

		fmt.Println("Setting config")
		switch runtime.GOOS {

		case "windows":
			err = configOnWindows()
			if err != nil {
				panic(err)
			}
		default:
			fmt.Println("Not supported operating system")
		}
		fmt.Println("Install success")
	} else if *inst {
		if !IsExistInstaller() {
			fmt.Println("Downloading install program...")
			err := pull(PULL_INSTALLER)
			if err != nil {
				panic(err)
			}
			fmt.Println("Download Success")
		}
		fmt.Println("Installing...")

		reactiveHandler := common.ReactiveHandlerOnOS{HandleFunc: map[string]func(context.Context) (context.Context, error){}}
		reactiveHandler.HandleFunc["windows"] = installOnWindows
		_, err := reactiveHandler.Handle(context.Background())
		if err != nil {
			panic(err)
		}

		fmt.Println("Install success")
	}

	// if *inst {
	// 	if _, err := os.Stat(filepath.Join(workPath, "typora-installer")); err != nil {
	// 		fmt.Println("Start download")
	// 		download()
	// 		fmt.Println("download success")
	// 		fmt.Println("Start unzip")
	// 		unzip("main.zip")
	// 		fmt.Println("Unzip success")
	// 	}

	// 	fmt.Println("Installing...")
	// 	install()
	// 	fmt.Println("Install success")
	// } else if *conf {
	// 	if _, err := os.Stat(filepath.Join(workPath, "typora-installer")); err != nil {
	// 		fmt.Println("Start download")
	// 		download()
	// 		fmt.Println("download success")
	// 		fmt.Println("Start unzip")
	// 		unzip("main.zip")
	// 		fmt.Println("Unzip success")
	// 	}
	// 	fmt.Println("Set config")
	// 	config()
	// 	fmt.Println("Config success")
	// }
}
