package main

import (
	"errors"
    "io"
	"strings"
	"net/http"
    "encoding/json"
    "io/ioutil"
    "path/filepath"

	"fmt"
	"net"
	"os"
	"os/exec"
	"runtime"
	"strconv"
	"time"

	"localshow/files"
)

var MEDIA_PATH = "./"
var file_dict = map[string][]string{}
var ping_dict = map[string][]string{}

func openBrowser(url string) {
	switch runtime.GOOS {
	case "linux":
		exec.Command("xdg-open", url).Start()
	case "windows":
		exec.Command("rundll32", "url.dll,FileProtocolHandler", url).Start()
	case "darwin":
		exec.Command("open", url).Start()
	default:
		print(fmt.Errorf("unsupported platform"))
	}
}

func findAvailablePort(port int) string {
	for true {
		host_string := "127.0.0.1"
		port_string := strconv.Itoa(port)

		port_usable_1 := true
		timeout := time.Millisecond * 300
		conn, err := net.DialTimeout("tcp", net.JoinHostPort(host_string, port_string), timeout)
		if conn != nil {
			defer conn.Close()
		}
		if err != nil {
			port_usable_1 = true
		} else {
			port_usable_1 = false
		}

		port_usable_2 := true
		connection, err := net.Listen("tcp", ":"+port_string)
		if connection != nil {
			defer connection.Close()
		}
		if err != nil {
			port_usable_2 = false
		} else {
			port_usable_2 = true
		}

		if port_usable_1 && port_usable_2 {
			break
		} else {
			port = port + 1
		}
	}

	return strconv.Itoa(port)
}

func request_hello(response http.ResponseWriter, request *http.Request) {
    fmt.Printf("method: %v, path: %v, full: %v, source: %v \n", request.Method, request.URL.Path, request.URL.String(), request.RemoteAddr)

    response.Header().Set(
        "Content-Type",
        "text/html",
    )
    io.WriteString(
        response,
        `<DOCTYPE html>
        <html>
        <head>
            <title>Hello, World</title>
        </head>
        <body>
            hi! welcome to localshow! <a href="./ui">go and enjoy</a>
        </body>
        </html>`,
    )
}

func request_api(response http.ResponseWriter, request *http.Request) {
    if request.Method == http.MethodPost {
        body, _ := ioutil.ReadAll(request.Body)
        defer request.Body.Close()
        the_post_text := string(body)
        fmt.Printf("post data from /api: %v\n", the_post_text)
    }

    response.Header().Set("Content-Type", "application/json")
    response.Write([]byte(`{"msg": "hello"}`))
}

func request_info(response http.ResponseWriter, request *http.Request) {
    data := map[string]interface{}{
        "root_folder": MEDIA_PATH,
        "author": []string{"yingshaoxo", "xo"},
    }
    body, _ := json.Marshal(data)
    response.Header().Set("Content-Type", "application/json; charset=utf-8")
    response.Write(body)
}

func request_update(response http.ResponseWriter, request *http.Request) {
    file_dict, _ = files.Get_all_dir_and_files(MEDIA_PATH)

    data := map[string]interface{}{
        "status": "success",
    }
    body, _ := json.Marshal(data)
    response.Header().Set("Content-Type", "application/json; charset=utf-8")
    response.Write(body)
}

func request_files(response http.ResponseWriter, request *http.Request) {
    body, _ := json.Marshal(file_dict)
    response.Header().Set("Content-Type", "application/json; charset=utf-8")
    response.Write(body)
}

func request_ping(response http.ResponseWriter, request *http.Request) {
    body, _ := json.Marshal(ping_dict)
    response.Header().Set("Content-Type", "application/json; charset=utf-8")
    response.Write(body)
}

func main() {
	// get cli args
	dir, _ := os.Getwd()
    full_path_of_ui, _ := filepath.Abs("./ui")

	MEDIA_PATH = dir //"/media"
	if len(os.Args) >= 2 {
		MEDIA_PATH = os.Args[1]
		if path_info, err := os.Stat(MEDIA_PATH); os.IsNotExist(err) {
			err := errors.New(fmt.Sprintf("The folder you gave is not exists: %s", MEDIA_PATH))
			panic(err)
		} else {
			if !path_info.IsDir() {
				err := errors.New(fmt.Sprintf("The path you gave is not directory: %s", MEDIA_PATH))
				panic(err)
			} else {
				err := os.Chdir(MEDIA_PATH)
				if err != nil {
					panic(err)
				}
			}
		}
	}

	// ping
	ping_dict := map[string]string{
		"name":    "local_show",
		"sub_url": "/ui",
	}

	// Get all files
	file_dict, _ = files.Get_all_dir_and_files(MEDIA_PATH)
	//fmt.Println(file_dict)

	local_address := "127.0.0.1"
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		panic(err)
	}
	fmt.Printf("\n\n-------------------------------\n\n")

	port := findAvailablePort(5012)
	for _, addr := range addrs {
		lists := strings.Split(addr.String(), "/")
		fmt.Printf("You can visit your media at: http://%v:%v/ui\n", lists[0], port)

		if strings.Contains(lists[0], "192.168") {
			local_address = lists[0]
		}
	}
    //fmt.Printf("\n\nYou can visit your media at: http://127.0.0.1:%v/ui\n", port)

	var target_url = "http://" + local_address + ":" + port + "/ui"
	go func() {
		fmt.Printf("\n\n-------------------------------\n\n")

		// Open link
		openBrowser(target_url)

		time.Sleep(2 * time.Second)

		ping_dict["url"] = target_url
	}()


    http_mixer := http.NewServeMux()

    http_mixer.HandleFunc("/", request_hello)
    http_mixer.HandleFunc("/api", request_api)

    http_mixer.Handle("/ui/", http.StripPrefix("/ui/", http.FileServer(http.Dir(full_path_of_ui))))

    http_mixer.HandleFunc("/api/info/", request_info)
    http_mixer.HandleFunc("/api/update/", request_update)
    http_mixer.HandleFunc("/api/files/", request_files)
    http_mixer.HandleFunc("/ping", request_ping)

    http_mixer.Handle("/media/", http.StripPrefix("/media/", http.FileServer(http.Dir(MEDIA_PATH))))
    http_mixer.Handle("/raw/", http.StripPrefix("/raw/", http.FileServer(http.Dir(MEDIA_PATH))))
    http_mixer.Handle("/html/", http.StripPrefix("/html/", http.FileServer(http.Dir(MEDIA_PATH))))
    
    http.ListenAndServe(":"+string(port), http_mixer)
}

