package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"strings"

	"path/filepath"

	filetype "gopkg.in/h2non/filetype.v1"
)

func getFileSize(s string) (size int64, err error) {
	f, err := os.Open(s)
	if err != nil {
		size = 0
		return
	}
	fi, err := f.Stat()
	if err == nil {
		size = fi.Size()
	} else {
		size = 0
	}
	return
}

// not able to detect audio/amr and requries linux local dependency, not good
// func getFileMime(s string) (mimetype string, err error) {
// 	if err := magicmime.Open(magicmime.MAGIC_MIME_TYPE | magicmime.MAGIC_SYMLINK | magicmime.MAGIC_ERROR); err != nil {
// 		log.Fatal(err)
// 		return "", err
// 	}
// 	defer magicmime.Close()

// 	mimetype, err = magicmime.TypeByFile(s)
// 	if err != nil {
// 		log.Fatalf("error occured during type lookup: %v", err)
// 	}
// 	//log.Printf("mime-type: %v", mimetype)
// 	return
// }

func getFileMime(s string) (mimetype string, ext string, err error) {
	buf, _ := ioutil.ReadFile(s)

	kind, unkwown := filetype.Match(buf)
	if unkwown != nil {
		fmt.Printf("Unkwown: %s", unkwown)
		return
	}
	mimetype = kind.MIME.Value
	ext = kind.Extension
	//fmt.Printf("File type: %s. MIME: %s\n", kind.Extension, kind.MIME.Value)
	return
}

func isMP3(path string) bool {
	mime, ext, err := getFileMime(path)
	if err != nil {
		return false
	}
	check1 := strings.EqualFold("mp3", ext)
	check2 := strings.EqualFold("audio/mpeg", mime)
	return check1 && check2
}

func isAmr(path string) bool {
	mime, ext, err := getFileMime(path)
	if err != nil {
		return false
	}
	check1 := strings.EqualFold("amr", ext)
	check2 := strings.EqualFold("audio/amr", mime)
	return check1 && check2
}

func isMP4(path string) bool {
	mime, ext, err := getFileMime(path)
	if err != nil {
		return false
	}
	check1 := strings.EqualFold("mp4", ext)
	check2 := strings.EqualFold("video/mp4", mime)
	return check1 && check2
}

func isJPG(path string) bool {
	mime, ext, err := getFileMime(path)
	if err != nil {
		return false
	}
	check1 := strings.EqualFold("jpg", ext)
	check2 := strings.EqualFold("image/jpeg", mime)
	return check1 && check2
}

//get file Info for uploading CRM attachment /files
func getFileInfo4CRM(path string) (info crmFileInfo, err error) {
	info.Name = filepath.Base(path) + filepath.Ext(path)
	info.Type, _, err = getFileMime(path)
	info.Size, err = getFileSize(path)
	return
}

func isFileExist(path string) bool {
	if _, err := os.Stat(path); os.IsNotExist(err) {
		// path/to/whatever does not exist
		return false
	}
	return true
}

func ensurePathExist(path string) {
	d := filepath.Dir(path)
	if !isFileExist(d) {
		log.Println("Creating path [" + d + "]")
		os.MkdirAll(d, 0700)
	}
}
