package models

import (
	"log"
)


type RaspFeedback struct {
	Id 			string 	`json:"id" gorm:"PRIMARY_KEY"`
	Addr        string `json:"addr"`
	Description string	`json:"description"`
	Complete 	bool	`json:"complete"`
}

func GetAllFeedBackList() ([]*RaspFeedback,error) {
	var list []*RaspFeedback
	if err := db.Model(&RaspFeedback{}).Find(&list).Error; err != nil {
		return nil,err
	}
	return list,nil
}

func IsComplete(id string)bool{
	var feedback RaspFeedback
	err:=db.Model(&RaspFeedback{}).Where("id=?",id).First(&feedback).Error
	if err!=nil{
		log.Println(err)
		return true
	}
	//fmt.Println(feedback)
	if feedback==(RaspFeedback{}){
		return true
	}
	return feedback.Complete
}

func IsCompleteByAddr(addr string)bool{
	var feedback RaspFeedback
	err:=db.Model(&RaspFeedback{}).Where("addr=?",addr).First(&feedback).Error
	if err!=nil{
		log.Println(err)
		return true
	}
	//fmt.Println(feedback)
	if feedback==(RaspFeedback{}){
		return true
	}
	return feedback.Complete
}

func AddFeedBack(fd RaspFeedback)bool{
	if err:=db.Create(&fd).Error;err != nil {
		db.Save(&fd)
		log.Println(err)
		return false
	}
	return true
}

func DelFeedBack(id string){
	err:=db.Delete(&RaspFeedback{}).Where("id=?",id).Error
	if err!=nil{
		log.Println(err)
	}
}

func DropFeedBack(){
	db.DropTable(&RaspFeedback{})
}

func Complete(fd RaspFeedback){
	db.Model(&fd).Update("Complete",true)

}

func DeleteCompleteFeedback(){
	err:=db.Where("complete=?",1).Delete(&RaspFeedback{}).Error
	if err!=nil{
		log.Println(err)
	}
}

func ExistsUncompletedFeedback(addr string) (bool,error){
	var count int64
	err := db.Model(&RaspFeedback{}).Where("addr=? and complete = 0 ",addr).Count(&count).Error
	if err != nil {
		return false,err
	}

	if count == 1 {
		return true,nil
	}
	return false,nil
}