package services

import (
	"fmt"
	"os"
	"strconv"
	"ticket-pimp/internal/domain"
	"ticket-pimp/internal/helpers"
	"time"
)

type Cloud struct {
	*CommonClient
}

type ICloud interface {
	CreateFolder(name string) (*domain.Folder, error)
}

func NewCloud(base, user, pass string) *Cloud {

	client := NewClient().
		SetTimeout(5*time.Second).
		SetCommonBasicAuth(user, pass).
		SetBaseURL(base)

	return &Cloud{
		CommonClient: &CommonClient{
			client,
		},
	}
}

func (c *Cloud) CreateFolder(name string) (*domain.Folder, error) {
	rootDir := os.Getenv("ROOTDIR")
	user := os.Getenv("CLOUD_USER")

	davPath := "/remote.php/dav/files/"
	parentPath := "/apps/files/?dir="

	name = helpers.GitNaming(name)

	cloud := domain.Folder{
		Title:      name,
		PrivateURL: "",
	}

	requestPath := davPath + user + rootDir + name

	cloud.PathTo = parentPath + rootDir + name

	resp, _ := c.R().
		Send("MKCOL", requestPath)

	if resp.IsSuccessState() {
		// Set stupid URL to the d entity
		cloud.PrivateURL = c.BaseURL + cloud.PathTo

		// Try to set short URL to the d entity
		if err := c.setPrivateURL(requestPath, &cloud); err != nil {
			return &cloud, err
		}
	} else {
		fmt.Println(resp.Status)
	}

	return &cloud, nil
}

func (c *Cloud) setPrivateURL(requestPath string, cloud *domain.Folder) error {

	payload := []byte(`<?xml version="1.0"?><a:propfind xmlns:a="DAV:" xmlns:oc="http://owncloud.org/ns"><a:prop><oc:fileid/></a:prop></a:propfind>`)

	// Deprecated: Read XML file
	/*
		xmlFile, err := ioutil.ReadFile("./fileid.xml") // moved into this method as a string..

		if err != nil {
			return fmt.Errorf("request xml file error: %v", err)
		}
	*/

	resp, _ := c.R().
		SetBody(payload).
		Send("PROPFIND", requestPath)

	if resp.Err != nil {
		return resp.Err
	}

	id := helpers.GetFileIDFromRespBody(resp.Bytes())

	if id == 0 {
		return fmt.Errorf("unable to get fileid")
	}

	cloud.PrivateURL = c.BaseURL + "/f/" + strconv.Itoa(id)

	return nil
}
