package main

import (
	"encoding/json"
	"fmt"
	"log"
	"testing"
	"time"
)

func TestCrmCreateEntity(t *testing.T) {

	e := crmdLead{}
	e.FirstName = "ff" + time.Now().Format(getCrmTimeLayout())
	e.LastName = "ll"
	e.Password = "pp"
	e.Status = "New"
	e.WechatHitxyID = time.Now().Format(getCrmTimeLayout())
	b, _ := json.Marshal(e)

	//Create
	entity, _ := crmCreateEntity("Lead", b)
	lead1, ok := entity.(crmdLead)
	AssertEqual(t, ok, true, "entity type should be crmdLead")

	//Read
	lead2, _ := crmGetLead(lead1.ID)
	AssertEqual(t, lead2.ID, lead1.ID, "lead id should be equal")

	//Update
	e.Password = "newpass"
	b, _ = json.Marshal(e)
	entity, _ = crmUpdateEntity("Lead", lead2.ID, b)
	lead3 := entity.(crmdLead)

	AssertEqual(t, lead3.ID, lead1.ID, "should be same lead")
	AssertEqual(t, lead3.Password, "newpass", "password should have been changed")
	AssertEqual(t, lead1.Password, "pp", "old password should be PP")

	//Delete this test lead.
	deleted, _ := crmDeleteEntity("Lead", lead1.ID)
	AssertEqual(t, deleted, true, "record should be deleted")

}

func TestCreateDuplicate(t *testing.T) {

	e := crmdLead{}
	e.FirstName = "ff" + time.Now().Format("2006-jan-02 03:04:05")
	e.LastName = "ll"
	e.Password = "pp"
	e.EmailAddress = "abc-non@gmail-exist.com"
	e.Status = "New"
	e.WechatHitxyID = "someopenid"
	b, _ := json.Marshal(e)

	//create
	entity, _ := crmCreateEntity("Lead", b)
	lead1 := entity.(crmdLead)

	//Read
	entity, _ = crmGetEntity("Lead", lead1.ID)
	lead2 := entity.(crmdLead)
	AssertEqual(t, lead1.ID, lead2.ID, "lead should have been created successfully")

	//try to create it again
	entity, err := crmCreateEntity("Lead", b)
	AssertEqual(t, err == nil, false, "should have error for duplicates")
	AssertEqual(t, isErrIndicateDuplicate(err), true, "the err should be duplicate error")
	lead3 := entity.(crmdLead)
	AssertEqual(t, lead1.ID, lead3.ID, "lead should have been created successfully")

	//delete
	deleted, _ := crmDeleteEntity("Lead", entity.(crmdLead).ID)
	AssertEqual(t, deleted, true, "test record should be deleted")
}

func TestCrmCreateEntityServerNotFound(t *testing.T) {

	e := crmdLead{}
	e.FirstName = "ff" + time.Now().Format("2006-jan-02 03:04:05")
	e.LastName = "ll"
	e.Password = "pp"
	e.Status = "New"
	e.WechatHitxyID = "someopenid"
	b, _ := json.Marshal(e)

	//temporarily change base url
	oldURL := CRMConfig.BaseURL
	CRMConfig.BaseURL = "https://not-exist.hitxy.org.au/" //
	entity, err := crmCreateEntity("Lead", b)
	CRMConfig.BaseURL = oldURL

	AssertEqual(t, isErrIndicateDuplicate(err), false, "this should not be a duplicate error")
	AssertEqual(t, entity, nil, "should not be able to create entity, it should be nil")

}

func TestCrmReplaceEntity(t *testing.T) {

	e := crmdLead{}
	e.FirstName = "ff1" + time.Now().Format("2006-jan-02 03:04:05")
	e.LastName = "ll1"
	e.Password = "pp"
	e.Status = "New"
	e.EmailAddress = "abc@gmail.com"
	e.WechatHitxyID = "someopenid"
	b, _ := json.Marshal(e)
	entity, err := crmCreateEntity("Lead", b)
	if err != nil {
		log.Println("--------------")
		log.Println(err)
		log.Println("--------------")
	}
	AssertEqual(t, err, nil, "create record should be successful")
	AssertEqual(t, isErrIndicateDuplicate(err), false, "this should not be a duplicate error")

	id := entity.(crmdLead).ID

	//put
	e.WechatHitxyID = "newid"
	e.Password = "newpass"
	nb, _ := json.Marshal(e)
	entity, err = crmReplaceEntity("Lead", id, nb)
	AssertEqual(t, err, nil, "put should have no error")
	AssertEqual(t, entity.(crmdLead).WechatHitxyID, "newid", "wechatOpenID should be updated")
	AssertEqual(t, entity.(crmdLead).Password, "newpass", "password should have been changed to newpass")

	//delete
	deleted, _ := crmDeleteEntity("Lead", id)
	AssertEqual(t, deleted, true, "test record should have been deleted.")
}

func TestSearchEntityByID(t *testing.T) {

	e := crmdLead{}
	e.FirstName = "ff1" + time.Now().Format("2006-Jan-02 03:04:05")
	e.LastName = "ll1"
	e.Password = "pp"
	e.Status = "New"
	//e.EmailAddress = "abc@gmail.com"
	e.WechatHitxyID = "someopenid"
	b, _ := json.Marshal(e)
	entity, err := crmCreateEntity("Lead", b)
	if err != nil {
		log.Println("--------------")
		log.Println(err)
		log.Println("--------------")
	}
	AssertEqual(t, err, nil, "create record should be successful")
	AssertEqual(t, isErrIndicateDuplicate(err), false, "this should not be a duplicate error")

	id := entity.(crmdLead).ID
	obj, err := crmFindEntityByID("Lead", id)
	AssertEqual(t, obj.(crmdLead).ID, id, "we should found the right id")

	deleted, _ := crmDeleteEntity("Lead", id)
	AssertEqual(t, deleted, true, "deleting temp record should be true")

}

func TestDeleteNonExistRecord(t *testing.T) {
	id := "someidthatisnotexistatall"
	deleted, _ := crmDeleteEntity("Lead", id)
	AssertEqual(t, deleted, false, "deleting non-exist record should be false")

}

func TestSearchByAttr(t *testing.T) {
	ids := []string{}

	for i := 0; i < 10; i++ {
		e := crmdLead{}
		e.FirstName = fmt.Sprintf("%s-%d-%s", "ff", i, time.Now().Format("2006-Jan-02 03:04:05"))
		e.LastName = fmt.Sprintf("%s-%d", "ll", i)
		e.Password = fmt.Sprintf("%s-pp-%d", "pp", i)
		e.Status = "New"
		e.EmailAddress = fmt.Sprintf("abc%d@gmail.com", i)
		e.WechatHitxyID = fmt.Sprintf("someopenid-%d", i)
		b, _ := json.Marshal(e)
		entity, _ := crmCreateEntity("Lead", b)
		ids = append(ids, entity.(crmdLead).ID)
		log.Printf("creating %s", ids[i])
	}

	//search
	for i := 0; i < 10; i++ {
		log.Printf("trying to match %d using email, %s", i, ids[i])
		total, list, err := crmFindEntityByAttr("Lead", "emailAddress", fmt.Sprintf("abc%d@gmail.com", i))
		result := list.([]crmdLead)
		AssertEqual(t, err, nil, "find by attr should have no error")
		AssertEqual(t, total, 1, "should have found 1 and only 1")
		AssertEqual(t, len(result), 1, "list should be 1 ")
		AssertEqual(t, result[0].ID, ids[i], "the id should be correct.")

		log.Printf("trying to match %d using WechatId,%s", i, ids[i])
		total, list, err = crmFindEntityByAttr("Lead", "wechatOpenID", fmt.Sprintf("someopenid-%d", i))
		result = list.([]crmdLead)
		AssertEqual(t, err, nil, "find by attr should have no error")
		AssertEqual(t, total, 1, "should have found 1 and only 1")
		AssertEqual(t, len(result), 1, "list should be 1 ")
		AssertEqual(t, result[0].ID, ids[i], "the id should be correct.")

	}

	for i := 0; i < 10; i++ {
		crmDeleteEntity("Lead", ids[i])
		log.Printf("deleting %s", ids[i])
	}
}
